Merge ghostlight-verse/dungeon-deru-page: Ghostlight Dungeon for Deru (phone page, turn history, Dungeon-owned accounts with Google sign-in via Heimdall, vault-seeded Begin with era and lens, places and routes, play gated on Ready, run-ahead elaboration, second-person narrator); cuts dungeon-host-return, dungeon-seeded-begin, dungeon-deru-page, dungeon-google-sign-in, dungeon-era-at-begin; Soul verdicts on host-return s1 s2, seeded-begin s1, connector-v4 s1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
400
Cargo.lock
generated
|
|
@ -37,6 +37,15 @@ dependencies = [
|
||||||
"subtle",
|
"subtle",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "aho-corasick"
|
||||||
|
version = "1.1.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
|
||||||
|
dependencies = [
|
||||||
|
"memchr",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "android_system_properties"
|
name = "android_system_properties"
|
||||||
version = "0.1.6"
|
version = "0.1.6"
|
||||||
|
|
@ -61,6 +70,28 @@ dependencies = [
|
||||||
"object",
|
"object",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "async-stream"
|
||||||
|
version = "0.3.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476"
|
||||||
|
dependencies = [
|
||||||
|
"async-stream-impl",
|
||||||
|
"futures-core",
|
||||||
|
"pin-project-lite",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "async-stream-impl"
|
||||||
|
version = "0.3.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn 2.0.119",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "async-trait"
|
name = "async-trait"
|
||||||
version = "0.1.92"
|
version = "0.1.92"
|
||||||
|
|
@ -84,6 +115,70 @@ version = "1.5.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "axum"
|
||||||
|
version = "0.8.9"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"
|
||||||
|
dependencies = [
|
||||||
|
"axum-core",
|
||||||
|
"axum-macros",
|
||||||
|
"bytes",
|
||||||
|
"form_urlencoded",
|
||||||
|
"futures-util",
|
||||||
|
"http",
|
||||||
|
"http-body",
|
||||||
|
"http-body-util",
|
||||||
|
"hyper",
|
||||||
|
"hyper-util",
|
||||||
|
"itoa",
|
||||||
|
"matchit",
|
||||||
|
"memchr",
|
||||||
|
"mime",
|
||||||
|
"percent-encoding",
|
||||||
|
"pin-project-lite",
|
||||||
|
"serde_core",
|
||||||
|
"serde_json",
|
||||||
|
"serde_path_to_error",
|
||||||
|
"serde_urlencoded",
|
||||||
|
"sync_wrapper",
|
||||||
|
"tokio",
|
||||||
|
"tower",
|
||||||
|
"tower-layer",
|
||||||
|
"tower-service",
|
||||||
|
"tracing",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "axum-core"
|
||||||
|
version = "0.5.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1"
|
||||||
|
dependencies = [
|
||||||
|
"bytes",
|
||||||
|
"futures-core",
|
||||||
|
"http",
|
||||||
|
"http-body",
|
||||||
|
"http-body-util",
|
||||||
|
"mime",
|
||||||
|
"pin-project-lite",
|
||||||
|
"sync_wrapper",
|
||||||
|
"tower-layer",
|
||||||
|
"tower-service",
|
||||||
|
"tracing",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "axum-macros"
|
||||||
|
version = "0.5.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "7aa268c23bfbbd2c4363b9cd302a4f504fb2a9dfe7e3451d66f35dd392e20aca"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn 2.0.119",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "base64"
|
name = "base64"
|
||||||
version = "0.22.1"
|
version = "0.22.1"
|
||||||
|
|
@ -288,6 +383,42 @@ dependencies = [
|
||||||
"syn 2.0.119",
|
"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",
|
||||||
|
"serde",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "cultnet-rs"
|
||||||
|
version = "0.1.0"
|
||||||
|
source = "git+https://github.com/GameCult/CultLib.git?rev=85f7024a35ea42cf9f0a0199a064526427150191#85f7024a35ea42cf9f0a0199a064526427150191"
|
||||||
|
dependencies = [
|
||||||
|
"aes-gcm",
|
||||||
|
"anyhow",
|
||||||
|
"base64",
|
||||||
|
"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]]
|
[[package]]
|
||||||
name = "cultnet-rs"
|
name = "cultnet-rs"
|
||||||
version = "0.2.0"
|
version = "0.2.0"
|
||||||
|
|
@ -350,6 +481,12 @@ dependencies = [
|
||||||
"zeroize",
|
"zeroize",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "deranged"
|
||||||
|
version = "0.5.9"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "digest"
|
name = "digest"
|
||||||
version = "0.10.7"
|
version = "0.10.7"
|
||||||
|
|
@ -594,6 +731,42 @@ dependencies = [
|
||||||
"zeroize",
|
"zeroize",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "ghostlight-dungeon"
|
||||||
|
version = "0.1.0"
|
||||||
|
dependencies = [
|
||||||
|
"aes-gcm",
|
||||||
|
"anyhow",
|
||||||
|
"async-stream",
|
||||||
|
"async-trait",
|
||||||
|
"axum",
|
||||||
|
"base64",
|
||||||
|
"chrono",
|
||||||
|
"cultcache-rs 0.1.0",
|
||||||
|
"cultmesh-rs",
|
||||||
|
"cultnet-rs 0.1.0",
|
||||||
|
"ghostlight",
|
||||||
|
"ghostlight-persona-projection",
|
||||||
|
"hmac",
|
||||||
|
"jsonwebtoken",
|
||||||
|
"libc",
|
||||||
|
"model-connector",
|
||||||
|
"rand 0.9.5",
|
||||||
|
"reqwest",
|
||||||
|
"rmp-serde",
|
||||||
|
"serde",
|
||||||
|
"serde_json",
|
||||||
|
"sha2",
|
||||||
|
"tempfile",
|
||||||
|
"thiserror",
|
||||||
|
"tokio",
|
||||||
|
"tower",
|
||||||
|
"tracing",
|
||||||
|
"tracing-subscriber",
|
||||||
|
"uuid",
|
||||||
|
"zeroize",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ghostlight-persona-projection"
|
name = "ghostlight-persona-projection"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
|
|
@ -663,6 +836,12 @@ version = "1.10.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
|
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "httpdate"
|
||||||
|
version = "1.0.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "hyper"
|
name = "hyper"
|
||||||
version = "1.11.0"
|
version = "1.11.0"
|
||||||
|
|
@ -676,6 +855,7 @@ dependencies = [
|
||||||
"http",
|
"http",
|
||||||
"http-body",
|
"http-body",
|
||||||
"httparse",
|
"httparse",
|
||||||
|
"httpdate",
|
||||||
"itoa",
|
"itoa",
|
||||||
"pin-project-lite",
|
"pin-project-lite",
|
||||||
"smallvec",
|
"smallvec",
|
||||||
|
|
@ -882,6 +1062,27 @@ dependencies = [
|
||||||
"wasm-bindgen",
|
"wasm-bindgen",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "jsonwebtoken"
|
||||||
|
version = "9.3.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "5a87cc7a48537badeae96744432de36f4be2b4a34a05a5ef32e9dd8a1c169dde"
|
||||||
|
dependencies = [
|
||||||
|
"base64",
|
||||||
|
"js-sys",
|
||||||
|
"pem",
|
||||||
|
"ring",
|
||||||
|
"serde",
|
||||||
|
"serde_json",
|
||||||
|
"simple_asn1",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "lazy_static"
|
||||||
|
version = "1.5.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "libc"
|
name = "libc"
|
||||||
version = "0.2.189"
|
version = "0.2.189"
|
||||||
|
|
@ -921,12 +1122,33 @@ version = "0.1.2"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
|
checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "matchers"
|
||||||
|
version = "0.2.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9"
|
||||||
|
dependencies = [
|
||||||
|
"regex-automata",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "matchit"
|
||||||
|
version = "0.8.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "memchr"
|
name = "memchr"
|
||||||
version = "2.8.3"
|
version = "2.8.3"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "mime"
|
||||||
|
version = "0.3.18"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "mio"
|
name = "mio"
|
||||||
version = "1.2.2"
|
version = "1.2.2"
|
||||||
|
|
@ -945,7 +1167,7 @@ source = "git+https://eureka.gamecult.org/forge/GameCult/ModelConnector.git?rev=
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"aes-gcm",
|
"aes-gcm",
|
||||||
"base64",
|
"base64",
|
||||||
"cultnet-rs",
|
"cultnet-rs 0.2.0",
|
||||||
"rand_core 0.6.4",
|
"rand_core 0.6.4",
|
||||||
"rmp-serde",
|
"rmp-serde",
|
||||||
"rmpv",
|
"rmpv",
|
||||||
|
|
@ -958,6 +1180,40 @@ dependencies = [
|
||||||
"zeroize",
|
"zeroize",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "nu-ansi-term"
|
||||||
|
version = "0.50.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
|
||||||
|
dependencies = [
|
||||||
|
"windows-sys 0.61.2",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "num-bigint"
|
||||||
|
version = "0.4.8"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"
|
||||||
|
dependencies = [
|
||||||
|
"num-integer",
|
||||||
|
"num-traits",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "num-conv"
|
||||||
|
version = "0.2.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "num-integer"
|
||||||
|
version = "0.1.47"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
|
||||||
|
dependencies = [
|
||||||
|
"num-traits",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "num-traits"
|
name = "num-traits"
|
||||||
version = "0.2.19"
|
version = "0.2.19"
|
||||||
|
|
@ -1011,6 +1267,16 @@ dependencies = [
|
||||||
"windows-link",
|
"windows-link",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "pem"
|
||||||
|
version = "3.0.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be"
|
||||||
|
dependencies = [
|
||||||
|
"base64",
|
||||||
|
"serde_core",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "percent-encoding"
|
name = "percent-encoding"
|
||||||
version = "2.3.2"
|
version = "2.3.2"
|
||||||
|
|
@ -1054,6 +1320,12 @@ dependencies = [
|
||||||
"zerovec",
|
"zerovec",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "powerfmt"
|
||||||
|
version = "0.2.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ppv-lite86"
|
name = "ppv-lite86"
|
||||||
version = "0.2.21"
|
version = "0.2.21"
|
||||||
|
|
@ -1261,6 +1533,23 @@ dependencies = [
|
||||||
"syn 3.0.3",
|
"syn 3.0.3",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "regex-automata"
|
||||||
|
version = "0.4.19"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158"
|
||||||
|
dependencies = [
|
||||||
|
"aho-corasick",
|
||||||
|
"memchr",
|
||||||
|
"regex-syntax",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "regex-syntax"
|
||||||
|
version = "0.8.12"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "reqwest"
|
name = "reqwest"
|
||||||
version = "0.12.28"
|
version = "0.12.28"
|
||||||
|
|
@ -1522,6 +1811,17 @@ dependencies = [
|
||||||
"zmij",
|
"zmij",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "serde_path_to_error"
|
||||||
|
version = "0.1.20"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457"
|
||||||
|
dependencies = [
|
||||||
|
"itoa",
|
||||||
|
"serde",
|
||||||
|
"serde_core",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "serde_stacker"
|
name = "serde_stacker"
|
||||||
version = "0.1.14"
|
version = "0.1.14"
|
||||||
|
|
@ -1556,6 +1856,15 @@ dependencies = [
|
||||||
"digest",
|
"digest",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "sharded-slab"
|
||||||
|
version = "0.1.7"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6"
|
||||||
|
dependencies = [
|
||||||
|
"lazy_static",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "shlex"
|
name = "shlex"
|
||||||
version = "2.0.1"
|
version = "2.0.1"
|
||||||
|
|
@ -1581,6 +1890,18 @@ dependencies = [
|
||||||
"rand_core 0.6.4",
|
"rand_core 0.6.4",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "simple_asn1"
|
||||||
|
version = "0.6.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0d585997b0ac10be3c5ee635f1bab02d512760d14b7c468801ac8a01d9ae5f1d"
|
||||||
|
dependencies = [
|
||||||
|
"num-bigint",
|
||||||
|
"num-traits",
|
||||||
|
"thiserror",
|
||||||
|
"time",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "slab"
|
name = "slab"
|
||||||
version = "0.4.12"
|
version = "0.4.12"
|
||||||
|
|
@ -1723,6 +2044,45 @@ dependencies = [
|
||||||
"syn 3.0.3",
|
"syn 3.0.3",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "thread_local"
|
||||||
|
version = "1.1.10"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070"
|
||||||
|
dependencies = [
|
||||||
|
"cfg-if",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "time"
|
||||||
|
version = "0.3.55"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134"
|
||||||
|
dependencies = [
|
||||||
|
"deranged",
|
||||||
|
"num-conv",
|
||||||
|
"powerfmt",
|
||||||
|
"serde_core",
|
||||||
|
"time-core",
|
||||||
|
"time-macros",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "time-core"
|
||||||
|
version = "0.1.9"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "time-macros"
|
||||||
|
version = "0.2.32"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85"
|
||||||
|
dependencies = [
|
||||||
|
"num-conv",
|
||||||
|
"time-core",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tinystr"
|
name = "tinystr"
|
||||||
version = "0.8.4"
|
version = "0.8.4"
|
||||||
|
|
@ -1812,6 +2172,7 @@ dependencies = [
|
||||||
"tokio",
|
"tokio",
|
||||||
"tower-layer",
|
"tower-layer",
|
||||||
"tower-service",
|
"tower-service",
|
||||||
|
"tracing",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -1850,6 +2211,7 @@ version = "0.1.44"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
|
checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"log",
|
||||||
"pin-project-lite",
|
"pin-project-lite",
|
||||||
"tracing-attributes",
|
"tracing-attributes",
|
||||||
"tracing-core",
|
"tracing-core",
|
||||||
|
|
@ -1873,6 +2235,36 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
|
checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"once_cell",
|
"once_cell",
|
||||||
|
"valuable",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tracing-log"
|
||||||
|
version = "0.2.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3"
|
||||||
|
dependencies = [
|
||||||
|
"log",
|
||||||
|
"once_cell",
|
||||||
|
"tracing-core",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tracing-subscriber"
|
||||||
|
version = "0.3.23"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319"
|
||||||
|
dependencies = [
|
||||||
|
"matchers",
|
||||||
|
"nu-ansi-term",
|
||||||
|
"once_cell",
|
||||||
|
"regex-automata",
|
||||||
|
"sharded-slab",
|
||||||
|
"smallvec",
|
||||||
|
"thread_local",
|
||||||
|
"tracing",
|
||||||
|
"tracing-core",
|
||||||
|
"tracing-log",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -1960,6 +2352,12 @@ dependencies = [
|
||||||
"wasm-bindgen",
|
"wasm-bindgen",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "valuable"
|
||||||
|
version = "0.1.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "version_check"
|
name = "version_check"
|
||||||
version = "0.9.5"
|
version = "0.9.5"
|
||||||
|
|
|
||||||
11
Cargo.toml
|
|
@ -1,6 +1,7 @@
|
||||||
[workspace]
|
[workspace]
|
||||||
members = [
|
members = [
|
||||||
"crates/ghostlight",
|
"crates/ghostlight",
|
||||||
|
"crates/ghostlight-dungeon",
|
||||||
"crates/ghostlight-persona-projection",
|
"crates/ghostlight-persona-projection",
|
||||||
"crates/ghostlight-verse",
|
"crates/ghostlight-verse",
|
||||||
]
|
]
|
||||||
|
|
@ -13,10 +14,19 @@ version = "0.1.0"
|
||||||
|
|
||||||
[workspace.dependencies]
|
[workspace.dependencies]
|
||||||
anyhow = "1"
|
anyhow = "1"
|
||||||
|
aes-gcm = "0.10"
|
||||||
async-trait = "0.1"
|
async-trait = "0.1"
|
||||||
|
async-stream = "0.3"
|
||||||
|
axum = { version = "0.8", features = ["macros"] }
|
||||||
chrono = { version = "0.4", features = ["serde"] }
|
chrono = { version = "0.4", features = ["serde"] }
|
||||||
|
base64 = "0.22"
|
||||||
model-connector = { git = "https://eureka.gamecult.org/forge/GameCult/ModelConnector.git", rev = "edf2f8e03cbb61df385b9b145b46f676ce3b70d5" }
|
model-connector = { git = "https://eureka.gamecult.org/forge/GameCult/ModelConnector.git", rev = "edf2f8e03cbb61df385b9b145b46f676ce3b70d5" }
|
||||||
cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "85f7024a35ea42cf9f0a0199a064526427150191", package = "cultcache-rs" }
|
cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "85f7024a35ea42cf9f0a0199a064526427150191", package = "cultcache-rs" }
|
||||||
|
cultnet-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "85f7024a35ea42cf9f0a0199a064526427150191", package = "cultnet-rs" }
|
||||||
|
cultmesh-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "85f7024a35ea42cf9f0a0199a064526427150191", package = "cultmesh-rs" }
|
||||||
|
jsonwebtoken = "9"
|
||||||
|
hmac = "0.12"
|
||||||
|
rand = "0.9"
|
||||||
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls", "stream"] }
|
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls", "stream"] }
|
||||||
rmp-serde = "1.3"
|
rmp-serde = "1.3"
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
|
|
@ -25,6 +35,7 @@ sha2 = "0.10"
|
||||||
thiserror = "2"
|
thiserror = "2"
|
||||||
tokio = { version = "1", features = ["full"] }
|
tokio = { version = "1", features = ["full"] }
|
||||||
tracing = "0.1"
|
tracing = "0.1"
|
||||||
|
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||||
unicode-segmentation = "1"
|
unicode-segmentation = "1"
|
||||||
uuid = { version = "1", features = ["v4", "serde"] }
|
uuid = { version = "1", features = ["v4", "serde"] }
|
||||||
zeroize = "1.8"
|
zeroize = "1.8"
|
||||||
|
|
|
||||||
46
crates/ghostlight-dungeon/Cargo.toml
Normal file
|
|
@ -0,0 +1,46 @@
|
||||||
|
[package]
|
||||||
|
name = "ghostlight-dungeon"
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
autobins = false
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "ghostlight-dungeon"
|
||||||
|
path = "src/main.rs"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
anyhow.workspace = true
|
||||||
|
aes-gcm.workspace = true
|
||||||
|
async-trait.workspace = true
|
||||||
|
async-stream.workspace = true
|
||||||
|
axum.workspace = true
|
||||||
|
chrono.workspace = true
|
||||||
|
base64.workspace = true
|
||||||
|
cultcache-rs.workspace = true
|
||||||
|
model-connector.workspace = true
|
||||||
|
cultnet-rs.workspace = true
|
||||||
|
cultmesh-rs.workspace = true
|
||||||
|
jsonwebtoken.workspace = true
|
||||||
|
libc = "0.2"
|
||||||
|
hmac.workspace = true
|
||||||
|
ghostlight = { path = "../ghostlight" }
|
||||||
|
ghostlight-persona-projection = { path = "../ghostlight-persona-projection" }
|
||||||
|
rand.workspace = true
|
||||||
|
reqwest.workspace = true
|
||||||
|
rmp-serde.workspace = true
|
||||||
|
serde.workspace = true
|
||||||
|
serde_json.workspace = true
|
||||||
|
sha2.workspace = true
|
||||||
|
thiserror.workspace = true
|
||||||
|
tokio.workspace = true
|
||||||
|
tracing.workspace = true
|
||||||
|
tracing-subscriber.workspace = true
|
||||||
|
uuid.workspace = true
|
||||||
|
zeroize.workspace = true
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
ghostlight = { path = "../ghostlight", features = ["test-support"] }
|
||||||
|
tempfile = "3"
|
||||||
|
tokio = { workspace = true, features = ["test-util"] }
|
||||||
|
tower = { version = "0.5", features = ["util"] }
|
||||||
65
crates/ghostlight-dungeon/build.rs
Normal file
|
|
@ -0,0 +1,65 @@
|
||||||
|
use std::{env, path::Path, process::Command};
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
println!("cargo:rerun-if-env-changed=GHOSTLIGHT_BUILD_COMMIT");
|
||||||
|
let manifest_dir =
|
||||||
|
env::var("CARGO_MANIFEST_DIR").expect("Cargo must supply CARGO_MANIFEST_DIR");
|
||||||
|
let repo_root = Path::new(&manifest_dir).join("../..");
|
||||||
|
emit_git_rerun_paths(&repo_root);
|
||||||
|
// Release tooling injects the clean-tree commit. Git discovery is only a
|
||||||
|
// convenience for local builds. The exact ref and reflog dependencies above
|
||||||
|
// keep that convenience from silently publishing stale provenance.
|
||||||
|
let commit = env::var("GHOSTLIGHT_BUILD_COMMIT")
|
||||||
|
.ok()
|
||||||
|
.filter(|value| is_commit(value))
|
||||||
|
.or_else(|| git_commit(&repo_root))
|
||||||
|
.expect("GhostlightDungeon builds require an exact 40-hex source commit");
|
||||||
|
println!("cargo:rustc-env=GHOSTLIGHT_BUILD_COMMIT={commit}");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn emit_git_rerun_paths(repo_root: &Path) {
|
||||||
|
for git_path in ["HEAD", "logs/HEAD", "packed-refs"] {
|
||||||
|
if let Some(path) = git_output(repo_root, &["rev-parse", "--git-path", git_path]) {
|
||||||
|
emit_rerun_path(repo_root, &path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(reference) = git_output(repo_root, &["symbolic-ref", "-q", "HEAD"])
|
||||||
|
&& let Some(path) = git_output(repo_root, &["rev-parse", "--git-path", &reference])
|
||||||
|
{
|
||||||
|
emit_rerun_path(repo_root, &path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn emit_rerun_path(repo_root: &Path, git_path: &str) {
|
||||||
|
let path = Path::new(git_path);
|
||||||
|
let resolved = if path.is_absolute() {
|
||||||
|
path.to_path_buf()
|
||||||
|
} else {
|
||||||
|
repo_root.join(path)
|
||||||
|
};
|
||||||
|
println!("cargo:rerun-if-changed={}", resolved.display());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn git_commit(repo_root: &Path) -> Option<String> {
|
||||||
|
git_output(repo_root, &["rev-parse", "HEAD"]).filter(|value| is_commit(value))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn git_output(repo_root: &Path, args: &[&str]) -> Option<String> {
|
||||||
|
let output = Command::new("git")
|
||||||
|
.args(args)
|
||||||
|
.current_dir(repo_root)
|
||||||
|
.output()
|
||||||
|
.ok()?;
|
||||||
|
if !output.status.success() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
String::from_utf8(output.stdout)
|
||||||
|
.ok()
|
||||||
|
.map(|value| value.trim().to_owned())
|
||||||
|
.filter(|value| !value.is_empty())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_commit(value: &str) -> bool {
|
||||||
|
value.len() == 40 && value.bytes().all(|byte| byte.is_ascii_hexdigit())
|
||||||
|
}
|
||||||
25
crates/ghostlight-dungeon/page/index.html
Normal file
|
|
@ -0,0 +1,25 @@
|
||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||||
|
<meta name="color-scheme" content="dark light">
|
||||||
|
<meta name="referrer" content="no-referrer">
|
||||||
|
<title>Ghostlight Dungeon</title>
|
||||||
|
<link rel="stylesheet" href="page.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<header class="bar">
|
||||||
|
<button id="home" class="brand" type="button" aria-label="Your worlds">Ghostlight</button>
|
||||||
|
<div class="tools">
|
||||||
|
<button id="smaller" class="tool" type="button" aria-label="Smaller text">A−</button>
|
||||||
|
<button id="larger" class="tool" type="button" aria-label="Larger text">A+</button>
|
||||||
|
<button id="theme" class="tool" type="button" aria-label="Switch light or dark theme">◐</button>
|
||||||
|
<button id="signout" aria-label="Sign out" class="tool" type="button" hidden>Exit</button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
<main id="view" aria-live="polite"><p class="note">Loading…</p></main>
|
||||||
|
<noscript><p class="note">This page needs JavaScript to play.</p></noscript>
|
||||||
|
<script src="page.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
73
crates/ghostlight-dungeon/page/page.css
Normal file
|
|
@ -0,0 +1,73 @@
|
||||||
|
/* 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; }
|
||||||
410
crates/ghostlight-dungeon/page/page.js
Normal file
|
|
@ -0,0 +1,410 @@
|
||||||
|
// 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();
|
||||||
2198
crates/ghostlight-dungeon/src/api.rs
Normal file
954
crates/ghostlight-dungeon/src/app_session.rs
Normal file
|
|
@ -0,0 +1,954 @@
|
||||||
|
//! Local custody for authenticated Heimdall sessions.
|
||||||
|
//!
|
||||||
|
//! This store owns only browser-session continuity. It does not own world
|
||||||
|
//! selection, commands, idempotency, exports, or fictional state.
|
||||||
|
|
||||||
|
use crate::heimdall::{VerifiedSessionAdmission, VerifiedSessionRefresh};
|
||||||
|
use ghostlight::VerifiedPrincipalEvidence;
|
||||||
|
use aes_gcm::{Aes256Gcm, KeyInit, aead::Aead};
|
||||||
|
use anyhow::{Context, bail};
|
||||||
|
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore};
|
||||||
|
use rand::RngCore;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
use std::{collections::BTreeMap, path::Path};
|
||||||
|
|
||||||
|
const STORE_TYPE: &str = "ghostlight.app_session_store.v2";
|
||||||
|
/// `pub(crate)` so the recipe-drift test in `idunn_health.rs` can check the
|
||||||
|
/// `app-sessions` state slot's schema against this constant.
|
||||||
|
pub(crate) const STORE_SCHEMA: &str = "ghostlight.app_session_store.v2";
|
||||||
|
const STORE_KEY: &str = "primary";
|
||||||
|
const MAX_SESSION_RECORDS: usize = 1_024;
|
||||||
|
|
||||||
|
#[derive(Clone, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
struct AppSessionState {
|
||||||
|
schema: String,
|
||||||
|
sessions: BTreeMap<String, AppSession>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
struct AppSession {
|
||||||
|
schema: String,
|
||||||
|
cookie_hash: String,
|
||||||
|
account_subject_hash: String,
|
||||||
|
heimdall_session_id: String,
|
||||||
|
access_revision: u64,
|
||||||
|
verified_capabilities: Vec<String>,
|
||||||
|
access_expires_at: DateTime<Utc>,
|
||||||
|
refresh_expires_at: DateTime<Utc>,
|
||||||
|
encrypted_refresh_claim: String,
|
||||||
|
created_at: DateTime<Utc>,
|
||||||
|
last_refresh_at: DateTime<Utc>,
|
||||||
|
revoked_at: Option<DateTime<Utc>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The clause by which the local commit refuses a refresh Heimdall executed.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
|
||||||
|
pub(crate) enum RefreshRefusal {
|
||||||
|
#[error("local session was revoked during refresh")]
|
||||||
|
Revoked,
|
||||||
|
#[error("local session moved to another revision since the refresh candidate was taken")]
|
||||||
|
MovedSinceCandidate,
|
||||||
|
#[error("refresh receipt revision went backwards")]
|
||||||
|
RevisionWentBackwards,
|
||||||
|
#[error("refresh receipt names a different Heimdall session")]
|
||||||
|
SessionId,
|
||||||
|
#[error("refresh receipt names a different account")]
|
||||||
|
Account,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct RefreshCandidate {
|
||||||
|
pub(crate) cookie_hash: String,
|
||||||
|
pub(crate) account_subject_hash: String,
|
||||||
|
pub(crate) heimdall_session_id: String,
|
||||||
|
pub(crate) access_revision: u64,
|
||||||
|
pub(crate) refresh_claim: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct AppSessionOwner {
|
||||||
|
store: OwnedRedbMessagePackBackingStore,
|
||||||
|
row: CultCacheEnvelope,
|
||||||
|
state: AppSessionState,
|
||||||
|
wrapping_key: [u8; 32],
|
||||||
|
healthy: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AppSessionOwner {
|
||||||
|
pub(crate) fn open(
|
||||||
|
store_path: impl AsRef<Path>,
|
||||||
|
wrapping_key_path: impl AsRef<Path>,
|
||||||
|
) -> anyhow::Result<Self> {
|
||||||
|
let wrapping_key = read_wrapping_key(wrapping_key_path.as_ref())?;
|
||||||
|
let store = OwnedRedbMessagePackBackingStore::new(store_path.as_ref())?;
|
||||||
|
store
|
||||||
|
.validate_path_identity()
|
||||||
|
.context("app-session store path identity is invalid")?;
|
||||||
|
let rows = store.pull_all()?;
|
||||||
|
let (row, state) = match rows.as_slice() {
|
||||||
|
[] => {
|
||||||
|
let state = AppSessionState {
|
||||||
|
schema: STORE_SCHEMA.into(),
|
||||||
|
sessions: BTreeMap::new(),
|
||||||
|
};
|
||||||
|
let row = envelope(&state)?;
|
||||||
|
if !store.compare_and_swap_batch(&[], vec![row.clone()])? {
|
||||||
|
bail!("app-session store changed during initialization");
|
||||||
|
}
|
||||||
|
(row, state)
|
||||||
|
}
|
||||||
|
[row]
|
||||||
|
if row.r#type == STORE_TYPE
|
||||||
|
&& row.key == STORE_KEY
|
||||||
|
&& row.schema_id.as_deref() == Some(STORE_SCHEMA) =>
|
||||||
|
{
|
||||||
|
let state: AppSessionState =
|
||||||
|
rmp_serde::from_slice(&row.payload).context("app-session state is corrupt")?;
|
||||||
|
if rmp_serde::to_vec_named(&state)? != row.payload {
|
||||||
|
bail!("app-session state is not canonical");
|
||||||
|
}
|
||||||
|
if state.schema != STORE_SCHEMA {
|
||||||
|
bail!("app-session state schema is invalid");
|
||||||
|
}
|
||||||
|
validate_state(&state, &wrapping_key)?;
|
||||||
|
(row.clone(), state)
|
||||||
|
}
|
||||||
|
_ => bail!(
|
||||||
|
"app-session v2 store contains foreign or legacy records; start with a fresh store"
|
||||||
|
),
|
||||||
|
};
|
||||||
|
Ok(Self {
|
||||||
|
store,
|
||||||
|
row,
|
||||||
|
state,
|
||||||
|
wrapping_key,
|
||||||
|
healthy: true,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn create_session(
|
||||||
|
&mut self,
|
||||||
|
input: VerifiedSessionAdmission,
|
||||||
|
) -> anyhow::Result<String> {
|
||||||
|
if !input
|
||||||
|
.capabilities()
|
||||||
|
.iter()
|
||||||
|
.any(|value| value == "app_access")
|
||||||
|
{
|
||||||
|
bail!("Heimdall session lacks app_access");
|
||||||
|
}
|
||||||
|
if input.account_id().trim().is_empty()
|
||||||
|
|| input.heimdall_session_id().trim().is_empty()
|
||||||
|
|| input.refresh_claim().is_empty()
|
||||||
|
|| input.refresh_expires_at() <= input.access_expires_at()
|
||||||
|
{
|
||||||
|
bail!("Heimdall session material is invalid");
|
||||||
|
}
|
||||||
|
let mut cookie = [0_u8; 32];
|
||||||
|
rand::rng().fill_bytes(&mut cookie);
|
||||||
|
let raw_cookie = URL_SAFE_NO_PAD.encode(cookie);
|
||||||
|
let cookie_hash = secret_hash(&raw_cookie);
|
||||||
|
let account_subject_hash = secret_hash(&format!("heimdall-account:{}", input.account_id()));
|
||||||
|
let now = Utc::now();
|
||||||
|
let session = AppSession {
|
||||||
|
schema: "ghostlight.app_session.v2".into(),
|
||||||
|
cookie_hash: cookie_hash.clone(),
|
||||||
|
account_subject_hash: account_subject_hash.clone(),
|
||||||
|
heimdall_session_id: input.heimdall_session_id().to_owned(),
|
||||||
|
access_revision: input.access_revision(),
|
||||||
|
verified_capabilities: input.capabilities().to_vec(),
|
||||||
|
access_expires_at: input.access_expires_at(),
|
||||||
|
refresh_expires_at: input.refresh_expires_at(),
|
||||||
|
encrypted_refresh_claim: wrap_refresh(
|
||||||
|
&self.wrapping_key,
|
||||||
|
&account_subject_hash,
|
||||||
|
input.heimdall_session_id(),
|
||||||
|
input.refresh_claim(),
|
||||||
|
)?,
|
||||||
|
created_at: now,
|
||||||
|
last_refresh_at: now,
|
||||||
|
revoked_at: None,
|
||||||
|
};
|
||||||
|
let mut next = self.state.clone();
|
||||||
|
for previous in next.sessions.values_mut().filter(|previous| {
|
||||||
|
previous.revoked_at.is_none()
|
||||||
|
&& previous.heimdall_session_id == input.heimdall_session_id()
|
||||||
|
}) {
|
||||||
|
previous.revoked_at = Some(now);
|
||||||
|
}
|
||||||
|
next.sessions.insert(cookie_hash, session);
|
||||||
|
self.commit(next)?;
|
||||||
|
Ok(raw_cookie)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn is_healthy(&self) -> bool {
|
||||||
|
self.healthy
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn validate_custody(&mut self) -> anyhow::Result<()> {
|
||||||
|
self.ensure_owned()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn account_for_cookie(
|
||||||
|
&mut self,
|
||||||
|
raw_cookie: &str,
|
||||||
|
now: DateTime<Utc>,
|
||||||
|
) -> anyhow::Result<Option<VerifiedPrincipalEvidence>> {
|
||||||
|
self.ensure_owned()?;
|
||||||
|
let Some(session) = self.state.sessions.get(&secret_hash(raw_cookie)) else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
Ok((session.revoked_at.is_none()
|
||||||
|
&& session.access_expires_at > now
|
||||||
|
&& session.refresh_expires_at > now
|
||||||
|
&& session
|
||||||
|
.verified_capabilities
|
||||||
|
.iter()
|
||||||
|
.any(|value| value == "app_access"))
|
||||||
|
.then(|| {
|
||||||
|
VerifiedPrincipalEvidence::new(
|
||||||
|
session.account_subject_hash.clone(),
|
||||||
|
session.access_expires_at,
|
||||||
|
)
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn revoke_cookie(&mut self, raw_cookie: &str) -> anyhow::Result<bool> {
|
||||||
|
self.ensure_owned()?;
|
||||||
|
let cookie_hash = secret_hash(raw_cookie);
|
||||||
|
let mut next = self.state.clone();
|
||||||
|
let Some(session) = next.sessions.get_mut(&cookie_hash) else {
|
||||||
|
return Ok(false);
|
||||||
|
};
|
||||||
|
if session.revoked_at.is_some() {
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
session.revoked_at = Some(Utc::now());
|
||||||
|
self.commit(next)?;
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn revoke_cookie_hash(&mut self, cookie_hash: &str) -> anyhow::Result<bool> {
|
||||||
|
self.ensure_owned()?;
|
||||||
|
let mut next = self.state.clone();
|
||||||
|
let Some(session) = next.sessions.get_mut(cookie_hash) else {
|
||||||
|
return Ok(false);
|
||||||
|
};
|
||||||
|
if session.revoked_at.is_some() {
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
session.revoked_at = Some(Utc::now());
|
||||||
|
self.commit(next)?;
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn session_for_logout(
|
||||||
|
&mut self,
|
||||||
|
raw_cookie: &str,
|
||||||
|
) -> anyhow::Result<Option<RefreshCandidate>> {
|
||||||
|
self.ensure_owned()?;
|
||||||
|
let Some(session) = self.state.sessions.get(&secret_hash(raw_cookie)) else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
match self.refresh_candidate(session) {
|
||||||
|
Ok(candidate) => Ok(Some(candidate)),
|
||||||
|
Err(error) => self.poison(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn sessions_due_for_refresh(
|
||||||
|
&mut self,
|
||||||
|
now: DateTime<Utc>,
|
||||||
|
refresh_before: chrono::Duration,
|
||||||
|
) -> anyhow::Result<Vec<RefreshCandidate>> {
|
||||||
|
self.ensure_owned()?;
|
||||||
|
let candidates = self
|
||||||
|
.state
|
||||||
|
.sessions
|
||||||
|
.values()
|
||||||
|
.filter(|session| {
|
||||||
|
session.revoked_at.is_none()
|
||||||
|
&& session.refresh_expires_at > now
|
||||||
|
&& session.access_expires_at <= now + refresh_before
|
||||||
|
})
|
||||||
|
.map(|session| self.refresh_candidate(session))
|
||||||
|
.collect::<anyhow::Result<Vec<_>>>();
|
||||||
|
match candidates {
|
||||||
|
Ok(candidates) => Ok(candidates),
|
||||||
|
Err(error) => self.poison(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn apply_refresh(
|
||||||
|
&mut self,
|
||||||
|
cookie_hash: &str,
|
||||||
|
expected_access_revision: u64,
|
||||||
|
input: VerifiedSessionRefresh,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
if !input
|
||||||
|
.capabilities()
|
||||||
|
.iter()
|
||||||
|
.any(|value| value == "app_access")
|
||||||
|
{
|
||||||
|
bail!("refreshed Heimdall session lacks app_access");
|
||||||
|
}
|
||||||
|
if input.refresh_claim().is_empty()
|
||||||
|
|| input.refresh_expires_at() <= input.access_expires_at()
|
||||||
|
{
|
||||||
|
bail!("refreshed Heimdall session material is invalid");
|
||||||
|
}
|
||||||
|
let mut next = self.state.clone();
|
||||||
|
let session = next
|
||||||
|
.sessions
|
||||||
|
.get_mut(cookie_hash)
|
||||||
|
.context("local session vanished during refresh")?;
|
||||||
|
if session.revoked_at.is_some() {
|
||||||
|
return Err(RefreshRefusal::Revoked.into());
|
||||||
|
}
|
||||||
|
if session.access_revision != expected_access_revision {
|
||||||
|
return Err(RefreshRefusal::MovedSinceCandidate.into());
|
||||||
|
}
|
||||||
|
// Heimdall's access_revision is a revocation epoch: refresh rotates
|
||||||
|
// the token at the same revision, so equal is the normal receipt and
|
||||||
|
// only a lower one is a refusal.
|
||||||
|
if input.access_revision() < expected_access_revision {
|
||||||
|
return Err(RefreshRefusal::RevisionWentBackwards.into());
|
||||||
|
}
|
||||||
|
if session.heimdall_session_id != input.heimdall_session_id() {
|
||||||
|
return Err(RefreshRefusal::SessionId.into());
|
||||||
|
}
|
||||||
|
if session.account_subject_hash
|
||||||
|
!= secret_hash(&format!("heimdall-account:{}", input.account_id()))
|
||||||
|
{
|
||||||
|
return Err(RefreshRefusal::Account.into());
|
||||||
|
}
|
||||||
|
session.access_revision = input.access_revision();
|
||||||
|
session.verified_capabilities = input.capabilities().to_vec();
|
||||||
|
session.access_expires_at = input.access_expires_at();
|
||||||
|
session.refresh_expires_at = input.refresh_expires_at();
|
||||||
|
session.encrypted_refresh_claim = wrap_refresh(
|
||||||
|
&self.wrapping_key,
|
||||||
|
&session.account_subject_hash,
|
||||||
|
&session.heimdall_session_id,
|
||||||
|
input.refresh_claim(),
|
||||||
|
)?;
|
||||||
|
session.last_refresh_at = Utc::now();
|
||||||
|
self.commit(next)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn refresh_candidate(&self, session: &AppSession) -> anyhow::Result<RefreshCandidate> {
|
||||||
|
Ok(RefreshCandidate {
|
||||||
|
cookie_hash: session.cookie_hash.clone(),
|
||||||
|
account_subject_hash: session.account_subject_hash.clone(),
|
||||||
|
heimdall_session_id: session.heimdall_session_id.clone(),
|
||||||
|
access_revision: session.access_revision,
|
||||||
|
refresh_claim: unwrap_refresh(
|
||||||
|
&self.wrapping_key,
|
||||||
|
&session.account_subject_hash,
|
||||||
|
&session.heimdall_session_id,
|
||||||
|
&session.encrypted_refresh_claim,
|
||||||
|
)?,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn commit(&mut self, mut next: AppSessionState) -> anyhow::Result<()> {
|
||||||
|
self.ensure_owned()?;
|
||||||
|
prune_sessions(&mut next, Utc::now());
|
||||||
|
let next_row = envelope(&next)?;
|
||||||
|
let swapped = self
|
||||||
|
.store
|
||||||
|
.compare_and_swap_batch(std::slice::from_ref(&self.row), vec![next_row.clone()]);
|
||||||
|
if !matches!(swapped, Ok(true)) {
|
||||||
|
return self.poison(anyhow::anyhow!(
|
||||||
|
"app-session commit outcome is uncertain; sole ownership was lost"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if self.store.validate_path_identity().is_err() {
|
||||||
|
return self.poison(anyhow::anyhow!(
|
||||||
|
"app-session store path changed after durable commit"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
self.row = next_row;
|
||||||
|
self.state = next;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ensure_owned(&mut self) -> anyhow::Result<()> {
|
||||||
|
if !self.healthy {
|
||||||
|
bail!("app-session custody is poisoned; reopen the owner");
|
||||||
|
}
|
||||||
|
if self.store.validate_path_identity().is_err() {
|
||||||
|
self.healthy = false;
|
||||||
|
bail!("app-session store ownership was lost");
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poison<T>(&mut self, error: anyhow::Error) -> anyhow::Result<T> {
|
||||||
|
self.healthy = false;
|
||||||
|
Err(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The idempotency key of the refresh that spends `refresh_claim`: a retry of
|
||||||
|
/// that refresh derives the same key, the next refresh (a new claim) a new one,
|
||||||
|
/// and the claim itself never leaves the process in it.
|
||||||
|
pub(crate) fn refresh_idempotency_key(refresh_claim: &str) -> String {
|
||||||
|
format!(
|
||||||
|
"refresh:{}",
|
||||||
|
secret_hash(&format!("heimdall-refresh-key:{refresh_claim}"))
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn secret_hash(value: &str) -> String {
|
||||||
|
format!("sha256:{:x}", Sha256::digest(value.as_bytes()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn envelope(state: &AppSessionState) -> anyhow::Result<CultCacheEnvelope> {
|
||||||
|
Ok(CultCacheEnvelope {
|
||||||
|
key: STORE_KEY.into(),
|
||||||
|
r#type: STORE_TYPE.into(),
|
||||||
|
payload: rmp_serde::to_vec_named(state)?,
|
||||||
|
stored_at: Utc::now().to_rfc3339(),
|
||||||
|
schema_id: Some(STORE_SCHEMA.into()),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn validate_state(state: &AppSessionState, wrapping_key: &[u8; 32]) -> anyhow::Result<()> {
|
||||||
|
if state.schema != STORE_SCHEMA {
|
||||||
|
bail!("app-session state schema is invalid");
|
||||||
|
}
|
||||||
|
for (key, session) in &state.sessions {
|
||||||
|
if key != &session.cookie_hash
|
||||||
|
|| !is_secret_hash(key)
|
||||||
|
|| !is_secret_hash(&session.account_subject_hash)
|
||||||
|
|| session.schema != "ghostlight.app_session.v2"
|
||||||
|
|| session.heimdall_session_id.trim().is_empty()
|
||||||
|
|| session.heimdall_session_id.trim() != session.heimdall_session_id
|
||||||
|
|| !session
|
||||||
|
.verified_capabilities
|
||||||
|
.iter()
|
||||||
|
.any(|value| value == "app_access")
|
||||||
|
|| session.refresh_expires_at <= session.access_expires_at
|
||||||
|
|| session.last_refresh_at < session.created_at
|
||||||
|
|| session
|
||||||
|
.revoked_at
|
||||||
|
.is_some_and(|revoked_at| revoked_at < session.created_at)
|
||||||
|
{
|
||||||
|
bail!("app-session state contains a noncanonical session");
|
||||||
|
}
|
||||||
|
unwrap_refresh(
|
||||||
|
wrapping_key,
|
||||||
|
&session.account_subject_hash,
|
||||||
|
&session.heimdall_session_id,
|
||||||
|
&session.encrypted_refresh_claim,
|
||||||
|
)
|
||||||
|
.context("app-session state contains an unreadable refresh claim")?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_secret_hash(value: &str) -> bool {
|
||||||
|
value.len() == 71
|
||||||
|
&& value.strip_prefix("sha256:").is_some_and(|hex| {
|
||||||
|
hex.bytes()
|
||||||
|
.all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn prune_sessions(state: &mut AppSessionState, now: DateTime<Utc>) {
|
||||||
|
let retention_floor = now - chrono::Duration::days(7);
|
||||||
|
state.sessions.retain(|_, session| {
|
||||||
|
session.refresh_expires_at > retention_floor
|
||||||
|
&& session
|
||||||
|
.revoked_at
|
||||||
|
.is_none_or(|revoked_at| revoked_at > retention_floor)
|
||||||
|
});
|
||||||
|
if state.sessions.len() <= MAX_SESSION_RECORDS {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let mut oldest = state
|
||||||
|
.sessions
|
||||||
|
.iter()
|
||||||
|
.map(|(key, session)| {
|
||||||
|
let live = session.revoked_at.is_none() && session.refresh_expires_at > now;
|
||||||
|
(live, session.last_refresh_at, key.clone())
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
oldest.sort();
|
||||||
|
for (_, _, key) in oldest
|
||||||
|
.into_iter()
|
||||||
|
.take(state.sessions.len() - MAX_SESSION_RECORDS)
|
||||||
|
{
|
||||||
|
state.sessions.remove(&key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_wrapping_key(path: &Path) -> anyhow::Result<[u8; 32]> {
|
||||||
|
let source = std::fs::read(path)
|
||||||
|
.with_context(|| format!("failed to read session wrapping key {}", path.display()))?;
|
||||||
|
let decoded = if source.len() == 32 {
|
||||||
|
source
|
||||||
|
} else {
|
||||||
|
URL_SAFE_NO_PAD
|
||||||
|
.decode(std::str::from_utf8(&source)?.trim())
|
||||||
|
.context("session wrapping key must be 32 raw bytes or base64url")?
|
||||||
|
};
|
||||||
|
decoded
|
||||||
|
.try_into()
|
||||||
|
.map_err(|_| anyhow::anyhow!("session wrapping key must be exactly 32 bytes"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn wrap_refresh(
|
||||||
|
key: &[u8; 32],
|
||||||
|
account_hash: &str,
|
||||||
|
session_id: &str,
|
||||||
|
claim: &str,
|
||||||
|
) -> anyhow::Result<String> {
|
||||||
|
let mut iv = [0_u8; 12];
|
||||||
|
rand::rng().fill_bytes(&mut iv);
|
||||||
|
let aad = format!("ghostlight.app_session.refresh.v2\n{account_hash}\n{session_id}");
|
||||||
|
let ciphertext = Aes256Gcm::new_from_slice(key)?
|
||||||
|
.encrypt(
|
||||||
|
(&iv).into(),
|
||||||
|
aes_gcm::aead::Payload {
|
||||||
|
msg: claim.as_bytes(),
|
||||||
|
aad: aad.as_bytes(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.map_err(|_| anyhow::anyhow!("failed to wrap Heimdall refresh claim"))?;
|
||||||
|
Ok(format!(
|
||||||
|
"{}.{}",
|
||||||
|
URL_SAFE_NO_PAD.encode(iv),
|
||||||
|
URL_SAFE_NO_PAD.encode(ciphertext)
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn unwrap_refresh(
|
||||||
|
key: &[u8; 32],
|
||||||
|
account_hash: &str,
|
||||||
|
session_id: &str,
|
||||||
|
wrapped: &str,
|
||||||
|
) -> anyhow::Result<String> {
|
||||||
|
let (iv, ciphertext) = wrapped
|
||||||
|
.split_once('.')
|
||||||
|
.context("wrapped refresh claim is malformed")?;
|
||||||
|
let iv: [u8; 12] = URL_SAFE_NO_PAD
|
||||||
|
.decode(iv)?
|
||||||
|
.try_into()
|
||||||
|
.map_err(|_| anyhow::anyhow!("wrapped refresh IV is invalid"))?;
|
||||||
|
let ciphertext = URL_SAFE_NO_PAD.decode(ciphertext)?;
|
||||||
|
let aad = format!("ghostlight.app_session.refresh.v2\n{account_hash}\n{session_id}");
|
||||||
|
let plaintext = Aes256Gcm::new_from_slice(key)?
|
||||||
|
.decrypt(
|
||||||
|
(&iv).into(),
|
||||||
|
aes_gcm::aead::Payload {
|
||||||
|
msg: &ciphertext,
|
||||||
|
aad: aad.as_bytes(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.map_err(|_| anyhow::anyhow!("failed to unwrap Heimdall refresh claim"))?;
|
||||||
|
String::from_utf8(plaintext).context("Heimdall refresh claim is not UTF-8")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
/// Every `.rs` file under `src`, subdirectories included, with everything
|
||||||
|
/// a `#[cfg(test)]` attribute guards removed — whatever that item is, and
|
||||||
|
/// whatever a test module is called.
|
||||||
|
///
|
||||||
|
/// The item's extent is read from the layout: an attribute at indent `N`
|
||||||
|
/// guards lines until the first later line at indent `N` that closes a
|
||||||
|
/// block, or, for an item with no body, until the first line at indent `N`
|
||||||
|
/// that ends in `;` or `,`. This is a claim about rustfmt's output, not
|
||||||
|
/// about Rust's grammar, and it is the reason the scan does not try to
|
||||||
|
/// balance braces: braces inside string and character literals are not
|
||||||
|
/// block structure, and a scanner that counts them reads the end of a test
|
||||||
|
/// module in the wrong place.
|
||||||
|
fn production_sources() -> Vec<(std::path::PathBuf, String)> {
|
||||||
|
fn indent(line: &str) -> usize {
|
||||||
|
line.len() - line.trim_start().len()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn strip_cfg_test(text: &str) -> String {
|
||||||
|
let lines: Vec<&str> = text.lines().collect();
|
||||||
|
let mut kept: Vec<&str> = Vec::new();
|
||||||
|
let mut index = 0;
|
||||||
|
while index < lines.len() {
|
||||||
|
let line = lines[index];
|
||||||
|
if line.trim() != "#[cfg(test)]" {
|
||||||
|
kept.push(line);
|
||||||
|
index += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let guard = indent(line);
|
||||||
|
index += 1;
|
||||||
|
// A body opens on the attribute's own item; without one, the
|
||||||
|
// item ends at its first terminator.
|
||||||
|
let mut opened = lines
|
||||||
|
.get(index)
|
||||||
|
.is_some_and(|next| next.trim_end().ends_with('{'));
|
||||||
|
while index < lines.len() {
|
||||||
|
let body = lines[index];
|
||||||
|
index += 1;
|
||||||
|
let trimmed = body.trim();
|
||||||
|
if trimmed.is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if opened {
|
||||||
|
if indent(body) == guard
|
||||||
|
&& (trimmed == "}" || trimmed == "};" || trimmed == "},")
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
} else if indent(body) == guard
|
||||||
|
&& (trimmed.ends_with(';') || trimmed.ends_with(','))
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
} else if indent(body) == guard && trimmed.ends_with('{') {
|
||||||
|
opened = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
kept.join("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut sources = Vec::new();
|
||||||
|
let mut pending = vec![std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src")];
|
||||||
|
while let Some(directory) = pending.pop() {
|
||||||
|
for entry in std::fs::read_dir(&directory).expect("the source tree reads") {
|
||||||
|
let path = entry.expect("a readable entry").path();
|
||||||
|
if path.is_dir() {
|
||||||
|
pending.push(path);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if path.extension().and_then(|value| value.to_str()) != Some("rs") {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let text = std::fs::read_to_string(&path)
|
||||||
|
.expect("the source reads")
|
||||||
|
.replace("\r\n", "\n");
|
||||||
|
sources.push((path, strip_cfg_test(&text)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sources
|
||||||
|
}
|
||||||
|
|
||||||
|
/// True when the text immediately following the type's name calls its
|
||||||
|
/// `new`. Written as a scan rather than one literal so the qualified
|
||||||
|
/// `<Type>::new(` form and any whitespace the formatter may introduce
|
||||||
|
/// count the same as the plain path.
|
||||||
|
fn calls_new(tail: &str) -> bool {
|
||||||
|
let tail = tail.trim_start();
|
||||||
|
let tail = tail.strip_prefix('>').unwrap_or(tail).trim_start();
|
||||||
|
let Some(tail) = tail.strip_prefix("::") else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let Some(tail) = tail.trim_start().strip_prefix("new") else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
tail.trim_start().starts_with('(')
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The library owns `VerifiedPrincipalEvidence` and gives it a public
|
||||||
|
/// constructor, so the single-minter rule its private fields used to
|
||||||
|
/// enforce is this one: production mints it in `account_for_cookie` and
|
||||||
|
/// nowhere else, from a live cookie this owner holds custody of. A second
|
||||||
|
/// minter anywhere in Dungeon's production source is a second authority
|
||||||
|
/// over who the kernel believes is speaking.
|
||||||
|
///
|
||||||
|
/// The type is followed by name, so production may not give it a second
|
||||||
|
/// name: an `as` import or a type alias is refused outright rather than
|
||||||
|
/// counted, because a renamed minter is one this test cannot follow. What
|
||||||
|
/// it still cannot see is a call that never spells the type — a macro
|
||||||
|
/// expansion, or a generic instantiated elsewhere.
|
||||||
|
#[test]
|
||||||
|
fn soul_exactly_one_production_site_mints_verified_principal_evidence() {
|
||||||
|
// Assembled from halves so this test's own source is never a match,
|
||||||
|
// whatever the scan above decides about this module's extent.
|
||||||
|
let name = format!("VerifiedPrincipal{}", "Evidence");
|
||||||
|
let mut sites = Vec::new();
|
||||||
|
for (path, production) in production_sources() {
|
||||||
|
for (at, _) in production.match_indices(name.as_str()) {
|
||||||
|
let tail = &production[at + name.len()..];
|
||||||
|
assert!(
|
||||||
|
!tail.trim_start().starts_with("as "),
|
||||||
|
"{} renames {name} on import",
|
||||||
|
path.display()
|
||||||
|
);
|
||||||
|
if calls_new(tail) {
|
||||||
|
sites.push(path.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for line in production.lines() {
|
||||||
|
assert!(
|
||||||
|
!(line.trim_start().starts_with("type ") && line.contains(name.as_str())),
|
||||||
|
"{} aliases {name} to another name: {line}",
|
||||||
|
path.display()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert_eq!(
|
||||||
|
sites.len(),
|
||||||
|
1,
|
||||||
|
"production mints {name} in exactly one place: {sites:?}"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
sites[0].ends_with("app_session.rs"),
|
||||||
|
"the one minter is not this owner: {:?}",
|
||||||
|
sites[0]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn a_cookie_authenticates_until_the_instant_its_access_expires() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let key = directory.path().join("session.key");
|
||||||
|
std::fs::write(&key, [23_u8; 32]).unwrap();
|
||||||
|
let mut owner = AppSessionOwner::open(directory.path().join("app-sessions-v2.cc"), &key).unwrap();
|
||||||
|
let now = Utc::now();
|
||||||
|
let (access, refresh) = (now + chrono::Duration::minutes(5), now + chrono::Duration::days(7));
|
||||||
|
let cookie = owner
|
||||||
|
.create_session(VerifiedSessionAdmission::fixture("a", "s1", 1, access, refresh, "c1"))
|
||||||
|
.unwrap();
|
||||||
|
assert!(owner.account_for_cookie(&cookie, access - chrono::Duration::seconds(1)).unwrap().is_some());
|
||||||
|
assert!(owner.account_for_cookie(&cookie, access).unwrap().is_none(), "dead at the instant");
|
||||||
|
assert!(owner.account_for_cookie("not-a-cookie", now).unwrap().is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn session(claim: &str) -> VerifiedSessionAdmission {
|
||||||
|
VerifiedSessionAdmission::fixture(
|
||||||
|
"account-1",
|
||||||
|
"heimdall-session-1",
|
||||||
|
3,
|
||||||
|
Utc::now() + chrono::Duration::minutes(5),
|
||||||
|
Utc::now() + chrono::Duration::days(7),
|
||||||
|
claim,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn store_rejects_an_alternate_messagepack_shape() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let key = directory.path().join("session.key");
|
||||||
|
std::fs::write(&key, [5_u8; 32]).unwrap();
|
||||||
|
let store_path = directory.path().join("app-sessions-v2.cc");
|
||||||
|
let store = OwnedRedbMessagePackBackingStore::new(&store_path).unwrap();
|
||||||
|
let state = AppSessionState {
|
||||||
|
schema: STORE_SCHEMA.into(),
|
||||||
|
sessions: BTreeMap::new(),
|
||||||
|
};
|
||||||
|
let row = CultCacheEnvelope {
|
||||||
|
key: STORE_KEY.into(),
|
||||||
|
r#type: STORE_TYPE.into(),
|
||||||
|
payload: rmp_serde::to_vec(&state).unwrap(),
|
||||||
|
stored_at: Utc::now().to_rfc3339(),
|
||||||
|
schema_id: Some(STORE_SCHEMA.into()),
|
||||||
|
};
|
||||||
|
assert!(store.compare_and_swap_batch(&[], vec![row]).unwrap());
|
||||||
|
drop(store);
|
||||||
|
assert!(AppSessionOwner::open(&store_path, &key).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn stores_only_session_custody_and_reopens() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let key = directory.path().join("session.key");
|
||||||
|
std::fs::write(&key, [7_u8; 32]).unwrap();
|
||||||
|
let store = directory.path().join("app-sessions-v2.cc");
|
||||||
|
let mut owner = AppSessionOwner::open(&store, &key).unwrap();
|
||||||
|
let cookie = owner
|
||||||
|
.create_session(session("private-refresh-claim"))
|
||||||
|
.unwrap();
|
||||||
|
let account = owner
|
||||||
|
.account_for_cookie(&cookie, Utc::now())
|
||||||
|
.unwrap()
|
||||||
|
.unwrap();
|
||||||
|
let account_hash = account.account_subject_hash().to_owned();
|
||||||
|
drop(owner);
|
||||||
|
|
||||||
|
let mut reopened = AppSessionOwner::open(&store, &key).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
reopened
|
||||||
|
.account_for_cookie(&cookie, Utc::now())
|
||||||
|
.unwrap()
|
||||||
|
.unwrap()
|
||||||
|
.account_subject_hash(),
|
||||||
|
account_hash
|
||||||
|
);
|
||||||
|
assert!(reopened.revoke_cookie(&cookie).unwrap());
|
||||||
|
assert_eq!(
|
||||||
|
reopened.account_for_cookie(&cookie, Utc::now()).unwrap(),
|
||||||
|
None
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn exact_heimdall_adoption_retry_rotates_the_only_live_cookie() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let key = directory.path().join("session.key");
|
||||||
|
std::fs::write(&key, [9_u8; 32]).unwrap();
|
||||||
|
let store = directory.path().join("app-sessions-v2.cc");
|
||||||
|
let mut owner = AppSessionOwner::open(&store, &key).unwrap();
|
||||||
|
let first = owner
|
||||||
|
.create_session(session("same-refresh-receipt"))
|
||||||
|
.unwrap();
|
||||||
|
let second = owner
|
||||||
|
.create_session(session("same-refresh-receipt"))
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert_ne!(first, second);
|
||||||
|
assert_eq!(owner.account_for_cookie(&first, Utc::now()).unwrap(), None);
|
||||||
|
assert!(
|
||||||
|
owner
|
||||||
|
.account_for_cookie(&second, Utc::now())
|
||||||
|
.unwrap()
|
||||||
|
.is_some()
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
owner
|
||||||
|
.state
|
||||||
|
.sessions
|
||||||
|
.values()
|
||||||
|
.filter(|session| session.revoked_at.is_none())
|
||||||
|
.count(),
|
||||||
|
1
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_legacy_or_foreign_store_instead_of_migrating_it() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let key = directory.path().join("session.key");
|
||||||
|
std::fs::write(&key, [3_u8; 32]).unwrap();
|
||||||
|
let store_path = directory.path().join("app-sessions-v2.cc");
|
||||||
|
let store = OwnedRedbMessagePackBackingStore::new(&store_path).unwrap();
|
||||||
|
let foreign = CultCacheEnvelope {
|
||||||
|
key: "primary".into(),
|
||||||
|
r#type: "app_session_store.v1".into(),
|
||||||
|
payload: vec![],
|
||||||
|
stored_at: Utc::now().to_rfc3339(),
|
||||||
|
schema_id: Some("ghostlight.app_session_store.v1".into()),
|
||||||
|
};
|
||||||
|
assert!(store.compare_and_swap_batch(&[], vec![foreign]).unwrap());
|
||||||
|
assert!(AppSessionOwner::open(&store_path, &key).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_refresh_for_a_session_that_moved_is_refused_by_name() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let key = directory.path().join("session.key");
|
||||||
|
std::fs::write(&key, [5_u8; 32]).unwrap();
|
||||||
|
let mut owner =
|
||||||
|
AppSessionOwner::open(directory.path().join("sessions.cc"), &key).unwrap();
|
||||||
|
let cookie = owner
|
||||||
|
.create_session(VerifiedSessionAdmission::fixture(
|
||||||
|
"account",
|
||||||
|
"session",
|
||||||
|
1,
|
||||||
|
Utc::now() + chrono::Duration::minutes(1),
|
||||||
|
Utc::now() + chrono::Duration::days(1),
|
||||||
|
"claim-0",
|
||||||
|
))
|
||||||
|
.unwrap();
|
||||||
|
let receipt = VerifiedSessionRefresh::fixture(
|
||||||
|
"account",
|
||||||
|
"session",
|
||||||
|
1,
|
||||||
|
Utc::now() + chrono::Duration::minutes(1),
|
||||||
|
Utc::now() + chrono::Duration::days(1),
|
||||||
|
"claim-1",
|
||||||
|
);
|
||||||
|
let error = owner
|
||||||
|
.apply_refresh(&secret_hash(&cookie), 0, receipt)
|
||||||
|
.unwrap_err();
|
||||||
|
assert_eq!(
|
||||||
|
error.downcast_ref::<RefreshRefusal>(),
|
||||||
|
Some(&RefreshRefusal::MovedSinceCandidate)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn refresh_claim_is_encrypted_and_exactly_bound() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let key = directory.path().join("session.key");
|
||||||
|
std::fs::write(&key, [11_u8; 32]).unwrap();
|
||||||
|
let store = directory.path().join("app-sessions-v2.cc");
|
||||||
|
let mut owner = AppSessionOwner::open(&store, &key).unwrap();
|
||||||
|
let cookie = owner
|
||||||
|
.create_session(session("needle-private-refresh"))
|
||||||
|
.unwrap();
|
||||||
|
let candidate = owner.session_for_logout(&cookie).unwrap().unwrap();
|
||||||
|
assert_eq!(candidate.refresh_claim, "needle-private-refresh");
|
||||||
|
drop(owner);
|
||||||
|
let bytes = std::fs::read(store).unwrap();
|
||||||
|
assert!(
|
||||||
|
!bytes
|
||||||
|
.windows("needle-private-refresh".len())
|
||||||
|
.any(|window| window == b"needle-private-refresh")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn replacing_the_store_path_revokes_session_authentication_until_reopen() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let key = directory.path().join("session.key");
|
||||||
|
std::fs::write(&key, [19_u8; 32]).unwrap();
|
||||||
|
let path = directory.path().join("app-sessions-v2.cc");
|
||||||
|
let displaced = directory.path().join("displaced.cc");
|
||||||
|
let mut owner = AppSessionOwner::open(&path, &key).unwrap();
|
||||||
|
let cookie = owner
|
||||||
|
.create_session(session("private-refresh-claim"))
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
std::fs::rename(&path, &displaced).unwrap();
|
||||||
|
std::fs::File::create(&path).unwrap();
|
||||||
|
assert!(owner.account_for_cookie(&cookie, Utc::now()).is_err());
|
||||||
|
assert!(!owner.is_healthy());
|
||||||
|
|
||||||
|
std::fs::remove_file(&path).unwrap();
|
||||||
|
std::fs::rename(&displaced, &path).unwrap();
|
||||||
|
assert!(owner.account_for_cookie(&cookie, Utc::now()).is_err());
|
||||||
|
drop(owner);
|
||||||
|
|
||||||
|
let mut reopened = AppSessionOwner::open(&path, &key).unwrap();
|
||||||
|
assert!(
|
||||||
|
reopened
|
||||||
|
.account_for_cookie(&cookie, Utc::now())
|
||||||
|
.unwrap()
|
||||||
|
.is_some()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reopen_rejects_corrupt_inner_session_custody() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let key = directory.path().join("session.key");
|
||||||
|
std::fs::write(&key, [23_u8; 32]).unwrap();
|
||||||
|
let path = directory.path().join("app-sessions-v2.cc");
|
||||||
|
let mut owner = AppSessionOwner::open(&path, &key).unwrap();
|
||||||
|
owner
|
||||||
|
.create_session(session("private-refresh-claim"))
|
||||||
|
.unwrap();
|
||||||
|
drop(owner);
|
||||||
|
|
||||||
|
let store = OwnedRedbMessagePackBackingStore::new(&path).unwrap();
|
||||||
|
let rows = store.pull_all().unwrap();
|
||||||
|
let mut state: AppSessionState = rmp_serde::from_slice(&rows[0].payload).unwrap();
|
||||||
|
state
|
||||||
|
.sessions
|
||||||
|
.values_mut()
|
||||||
|
.next()
|
||||||
|
.unwrap()
|
||||||
|
.encrypted_refresh_claim = "not-an-encrypted-claim".into();
|
||||||
|
let corrupt = envelope(&state).unwrap();
|
||||||
|
assert!(store.compare_and_swap_batch(&rows, vec![corrupt]).unwrap());
|
||||||
|
drop(store);
|
||||||
|
|
||||||
|
assert!(AppSessionOwner::open(&path, &key).is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
218
crates/ghostlight-dungeon/src/auth_guard.rs
Normal file
|
|
@ -0,0 +1,218 @@
|
||||||
|
//! What stands between the unauthenticated sign-in routes and the open internet.
|
||||||
|
//!
|
||||||
|
//! Browser binding. A Heimdall attempt handle is redeemable by whoever holds
|
||||||
|
//! it, so `begin` also mints a random secret, returns it to the beginning
|
||||||
|
//! browser as an HttpOnly cookie, and keeps only its hash against the handle.
|
||||||
|
//! `complete` must present that cookie, once, before the attempt expires: a
|
||||||
|
//! handle begun in one browser cannot be completed from another. This is the
|
||||||
|
//! OAuth `state` pattern (RFC 6749 section 10.12, CSRF on the redirect) and
|
||||||
|
//! the same binding PKCE (RFC 7636) gives a code: the party that starts the
|
||||||
|
//! flow holds a secret the interceptor never sees.
|
||||||
|
//!
|
||||||
|
//! Throttle. A fixed-window per-client counter on the same routes. Clients are
|
||||||
|
//! keyed by what the caller passes, which behind the reverse proxy is the
|
||||||
|
//! `X-Real-IP` value nginx sets.
|
||||||
|
|
||||||
|
use crate::app_session::secret_hash;
|
||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
use rand::RngCore;
|
||||||
|
use std::{collections::HashMap, sync::Mutex};
|
||||||
|
|
||||||
|
pub(crate) const BEGIN_COOKIE: &str = "ghostlight_auth";
|
||||||
|
/// How long a begun sign-in may stay open, whatever Heimdall allows.
|
||||||
|
pub(crate) const BEGIN_TTL_SECONDS: i64 = 600;
|
||||||
|
const MAX_PENDING: usize = 4096;
|
||||||
|
const WINDOW_SECONDS: i64 = 60;
|
||||||
|
const MAX_PER_WINDOW: u32 = 30;
|
||||||
|
const MAX_CLIENTS: usize = 8192;
|
||||||
|
|
||||||
|
struct Pending {
|
||||||
|
secret_hash: String,
|
||||||
|
expires_at: DateTime<Utc>,
|
||||||
|
/// The invite the browser presented at begin, held in memory only and for
|
||||||
|
/// no longer than the attempt lives. Spent by `catalog.sign_in` at complete.
|
||||||
|
invite: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
pub(crate) struct AuthGuard {
|
||||||
|
pending: Mutex<HashMap<String, Pending>>,
|
||||||
|
windows: Mutex<HashMap<String, (i64, u32)>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AuthGuard {
|
||||||
|
/// Opens a binding for `handle` and returns the secret for the browser's
|
||||||
|
/// cookie, or `None` when too many sign-ins are already open.
|
||||||
|
pub(crate) fn start(
|
||||||
|
&self,
|
||||||
|
handle: &str,
|
||||||
|
invite: Option<String>,
|
||||||
|
expires_at: DateTime<Utc>,
|
||||||
|
now: DateTime<Utc>,
|
||||||
|
) -> Option<String> {
|
||||||
|
let mut pending = self.pending.lock().expect("auth guard");
|
||||||
|
pending.retain(|_, attempt| attempt.expires_at > now);
|
||||||
|
if pending.len() >= MAX_PENDING {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let mut bytes = [0_u8; 32];
|
||||||
|
rand::rng().fill_bytes(&mut bytes);
|
||||||
|
let secret: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
|
||||||
|
pending.insert(
|
||||||
|
handle.to_owned(),
|
||||||
|
Pending {
|
||||||
|
secret_hash: secret_hash(&secret),
|
||||||
|
expires_at,
|
||||||
|
invite,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
Some(secret)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `secret` is the live binding for `handle`; spends nothing.
|
||||||
|
pub(crate) fn matches(&self, handle: &str, secret: &str, now: DateTime<Utc>) -> bool {
|
||||||
|
self.pending
|
||||||
|
.lock()
|
||||||
|
.expect("auth guard")
|
||||||
|
.get(handle)
|
||||||
|
.is_some_and(|attempt| attempt.expires_at > now && attempt.secret_hash == secret_hash(secret))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Spends the binding: `Some` exactly once for a live, matching secret,
|
||||||
|
/// carrying the invite bound at begin; `None` when this is not that
|
||||||
|
/// browser's attempt.
|
||||||
|
pub(crate) fn consume(&self, handle: &str, secret: &str, now: DateTime<Utc>) -> Option<Option<String>> {
|
||||||
|
let mut pending = self.pending.lock().expect("auth guard");
|
||||||
|
if !pending
|
||||||
|
.get(handle)
|
||||||
|
.is_some_and(|attempt| attempt.expires_at > now && attempt.secret_hash == secret_hash(secret))
|
||||||
|
{
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
pending.remove(handle).map(|attempt| attempt.invite)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Counts one request from `client`; false once it has used its window.
|
||||||
|
pub(crate) fn allow(&self, client: &str, now: DateTime<Utc>) -> bool {
|
||||||
|
let window = now.timestamp().div_euclid(WINDOW_SECONDS);
|
||||||
|
let mut windows = self.windows.lock().expect("auth guard");
|
||||||
|
if windows.len() >= MAX_CLIENTS {
|
||||||
|
windows.retain(|_, (started, _)| *started == window);
|
||||||
|
if windows.len() >= MAX_CLIENTS && !windows.contains_key(client) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let entry = windows.entry(client.to_owned()).or_insert((window, 0));
|
||||||
|
if entry.0 != window {
|
||||||
|
*entry = (window, 0);
|
||||||
|
}
|
||||||
|
entry.1 += 1;
|
||||||
|
entry.1 <= MAX_PER_WINDOW
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use chrono::Duration;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_binding_is_spent_once_and_only_by_its_own_secret_and_handle() {
|
||||||
|
let guard = AuthGuard::default();
|
||||||
|
let now = Utc::now();
|
||||||
|
let secret = guard.start("handle-a", None, now + Duration::minutes(5), now).unwrap();
|
||||||
|
let other = guard.start("handle-b", None, now + Duration::minutes(5), now).unwrap();
|
||||||
|
assert_ne!(secret, other);
|
||||||
|
assert_eq!(secret.len(), 64);
|
||||||
|
assert!(guard.matches("handle-a", &secret, now));
|
||||||
|
assert!(!guard.matches("handle-a", &other, now), "another begin's secret");
|
||||||
|
assert!(!guard.matches("handle-a", "", now));
|
||||||
|
assert!(!guard.matches("handle-unknown", &secret, now));
|
||||||
|
assert!(guard.consume("handle-a", &other, now).is_none());
|
||||||
|
assert!(guard.matches("handle-a", &secret, now), "a refused spend keeps the binding");
|
||||||
|
assert!(guard.consume("handle-a", &secret, now).is_some());
|
||||||
|
assert!(guard.consume("handle-a", &secret, now).is_none(), "single use");
|
||||||
|
assert!(!guard.matches("handle-a", &secret, now));
|
||||||
|
assert!(guard.consume("handle-b", &other, now).is_some(), "the other binding is untouched");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_invite_bound_at_begin_comes_back_once_to_the_beginning_browser_alone() {
|
||||||
|
let guard = AuthGuard::default();
|
||||||
|
let now = Utc::now();
|
||||||
|
let soon = now + Duration::minutes(5);
|
||||||
|
let secret = guard.start("h", Some("tok".into()), soon, now).unwrap();
|
||||||
|
let other = guard.start("g", None, soon, now).unwrap();
|
||||||
|
assert_eq!(guard.consume("h", &other, now), None, "another browser gets nothing and spends nothing");
|
||||||
|
assert_eq!(guard.consume("h", &secret, now), Some(Some("tok".into())));
|
||||||
|
assert_eq!(guard.consume("h", &secret, now), None);
|
||||||
|
assert_eq!(guard.consume("g", &other, now), Some(None), "no invite bound is still this browser's");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_binding_expires() {
|
||||||
|
let guard = AuthGuard::default();
|
||||||
|
let now = Utc::now();
|
||||||
|
let expiry = now + Duration::minutes(5);
|
||||||
|
let secret = guard.start("h", None, expiry, now).unwrap();
|
||||||
|
assert!(guard.matches("h", &secret, expiry - Duration::seconds(1)));
|
||||||
|
assert!(!guard.matches("h", &secret, expiry));
|
||||||
|
assert!(guard.consume("h", &secret, expiry).is_none());
|
||||||
|
assert!(guard.consume("h", &secret, expiry + Duration::hours(1)).is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn expired_bindings_are_dropped_and_the_open_set_is_bounded() {
|
||||||
|
let guard = AuthGuard::default();
|
||||||
|
let now = Utc::now();
|
||||||
|
for index in 0..MAX_PENDING {
|
||||||
|
assert!(guard.start(&format!("h{index}"), None, now + Duration::minutes(1), now).is_some());
|
||||||
|
}
|
||||||
|
assert!(guard.start("one-too-many", None, now + Duration::minutes(1), now).is_none());
|
||||||
|
let later = now + Duration::minutes(2);
|
||||||
|
assert!(guard.start("after-expiry", None, later + Duration::minutes(1), later).is_some());
|
||||||
|
assert_eq!(guard.pending.lock().unwrap().len(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_client_gets_a_fixed_window_and_clients_are_counted_apart() {
|
||||||
|
let guard = AuthGuard::default();
|
||||||
|
let start = DateTime::<Utc>::from_timestamp(1_000_020, 0).unwrap();
|
||||||
|
assert_eq!(start.timestamp() % WINDOW_SECONDS, 0);
|
||||||
|
for _ in 0..MAX_PER_WINDOW {
|
||||||
|
assert!(guard.allow("203.0.113.9", start));
|
||||||
|
}
|
||||||
|
assert!(!guard.allow("203.0.113.9", start + Duration::seconds(59)));
|
||||||
|
assert!(guard.allow("203.0.113.10", start + Duration::seconds(59)), "another client");
|
||||||
|
assert!(guard.allow("203.0.113.9", start + Duration::seconds(60)), "the next window");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_full_client_table_forgets_old_windows_and_refuses_strangers_not_counts() {
|
||||||
|
let guard = AuthGuard::default();
|
||||||
|
let start = DateTime::<Utc>::from_timestamp(1_000_020, 0).unwrap();
|
||||||
|
for index in 0..MAX_CLIENTS {
|
||||||
|
guard.allow(&format!("old{index}"), start);
|
||||||
|
}
|
||||||
|
let later = start + Duration::seconds(WINDOW_SECONDS);
|
||||||
|
for _ in 0..MAX_PER_WINDOW {
|
||||||
|
assert!(guard.allow("busy", later));
|
||||||
|
}
|
||||||
|
for index in 0..MAX_CLIENTS {
|
||||||
|
guard.allow(&format!("fresh{index}"), later);
|
||||||
|
}
|
||||||
|
assert!(!guard.allow("busy", later), "pruning keeps the current window's counts");
|
||||||
|
assert!(guard.windows.lock().unwrap().len() <= MAX_CLIENTS);
|
||||||
|
assert!(!guard.allow("brand-new", later), "a full table refuses a stranger rather than forget everyone");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_binding_is_dead_at_its_expiry_instant_and_dropped_by_the_next_start() {
|
||||||
|
let guard = AuthGuard::default();
|
||||||
|
let now = Utc::now();
|
||||||
|
guard.start("old", None, now + Duration::minutes(1), now).unwrap();
|
||||||
|
let at_expiry = now + Duration::minutes(1);
|
||||||
|
guard.start("new", None, at_expiry + Duration::minutes(1), at_expiry).unwrap();
|
||||||
|
assert_eq!(guard.pending.lock().unwrap().len(), 1, "expiry is exclusive");
|
||||||
|
}
|
||||||
|
}
|
||||||
1169
crates/ghostlight-dungeon/src/begin.rs
Normal file
699
crates/ghostlight-dungeon/src/catalog.rs
Normal file
|
|
@ -0,0 +1,699 @@
|
||||||
|
//! The catalog: which worlds exist, which timelines belong to them, and where
|
||||||
|
//! each player is standing.
|
||||||
|
//!
|
||||||
|
//! The kernel owns world state and `PlayTable` owns turns; this store owns only
|
||||||
|
//! the rows that say which store belongs to whom. One row holds all three
|
||||||
|
//! tables, written by compare-and-swap, so a world record and its root
|
||||||
|
//! timeline can never be seen apart.
|
||||||
|
|
||||||
|
use anyhow::{Context, bail, ensure};
|
||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::{collections::BTreeMap, path::Path};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
pub(crate) const STORE_TYPE: &str = "ghostlight.dungeon_catalog.v1";
|
||||||
|
const STORE_KEY: &str = "primary";
|
||||||
|
|
||||||
|
/// A world and who may play it. `snapshot_id` is the vault snapshot the world
|
||||||
|
/// was seeded from, `None` for a world that began unseeded.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub(crate) struct WorldRecord {
|
||||||
|
pub(crate) world_id: String,
|
||||||
|
pub(crate) title: String,
|
||||||
|
pub(crate) owner: String,
|
||||||
|
pub(crate) snapshot_id: Option<String>,
|
||||||
|
pub(crate) created_at: DateTime<Utc>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One playable line of a world. A fork records `(parent timeline, commit)`.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub(crate) struct Timeline {
|
||||||
|
pub(crate) id: String,
|
||||||
|
pub(crate) world_id: String,
|
||||||
|
pub(crate) parent: Option<(String, String)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where a timeline's seed stands. A timeline with no entry is Ready: it
|
||||||
|
/// began unseeded, or its seed finished. The entry is persisted with the
|
||||||
|
/// timeline so a restart cannot turn a Draft into a playable world.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub(crate) enum SeedStatus {
|
||||||
|
Seeding,
|
||||||
|
Failed(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A player's one pointer: which timeline they are in, and where they mean to
|
||||||
|
/// go next. Keyed by principal, so every device of one player reads the same.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub(crate) struct PlayerSession {
|
||||||
|
pub(crate) principal: String,
|
||||||
|
pub(crate) timeline: Option<String>,
|
||||||
|
pub(crate) destination: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// A Dungeon account: minted here, linked to the external identities Heimdall
|
||||||
|
/// authenticates. Heimdall holds no accounts.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub(crate) struct Account {
|
||||||
|
pub(crate) account_id: String,
|
||||||
|
pub(crate) identities: Vec<String>,
|
||||||
|
pub(crate) created_at: DateTime<Utc>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why a sign-in got no account.
|
||||||
|
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
|
||||||
|
pub(crate) enum SignInRefusal {
|
||||||
|
#[error("this sign-in has no account and no live invite")]
|
||||||
|
NoInvite,
|
||||||
|
}
|
||||||
|
#[derive(Clone, Default, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
struct CatalogState {
|
||||||
|
worlds: BTreeMap<String, WorldRecord>,
|
||||||
|
timelines: BTreeMap<String, Timeline>,
|
||||||
|
players: BTreeMap<String, PlayerSession>,
|
||||||
|
accounts: BTreeMap<String, Account>,
|
||||||
|
/// External identity (a Heimdall account id) to Dungeon account id.
|
||||||
|
identities: BTreeMap<String, String>,
|
||||||
|
/// Unconsumed invites: sha256 of the token to its expiry. Only the hash is kept.
|
||||||
|
invites: BTreeMap<String, DateTime<Utc>>,
|
||||||
|
/// Seeds that are not Ready, by timeline. Absent in a catalog that has
|
||||||
|
/// never held one, so older catalogs keep their canonical encoding.
|
||||||
|
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||||
|
seeds: BTreeMap<String, SeedStatus>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct Catalog {
|
||||||
|
store: OwnedRedbMessagePackBackingStore,
|
||||||
|
row: CultCacheEnvelope,
|
||||||
|
state: CatalogState,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `timeline:<uuid>`: the only shape that names a timeline, so the id can be a
|
||||||
|
/// directory name without ever carrying a path.
|
||||||
|
pub(crate) fn timeline_id(uuid: Uuid) -> String {
|
||||||
|
format!("timeline:{}", uuid.hyphenated())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The directory name a timeline id maps to, or `None` for anything that is
|
||||||
|
/// not exactly `timeline:<canonical uuid>`.
|
||||||
|
pub(crate) fn timeline_directory_name(id: &str) -> Option<String> {
|
||||||
|
let uuid = Uuid::parse_str(id.strip_prefix("timeline:")?).ok()?;
|
||||||
|
(timeline_id(uuid) == id).then(|| uuid.hyphenated().to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Catalog {
|
||||||
|
pub(crate) fn open(path: impl AsRef<Path>) -> anyhow::Result<Self> {
|
||||||
|
let store = OwnedRedbMessagePackBackingStore::new(path.as_ref())?;
|
||||||
|
store
|
||||||
|
.validate_path_identity()
|
||||||
|
.context("catalog store path identity is invalid")?;
|
||||||
|
let rows = store.pull_all()?;
|
||||||
|
let (row, state) = match rows.as_slice() {
|
||||||
|
[] => {
|
||||||
|
let state = CatalogState::default();
|
||||||
|
let row = envelope(&state)?;
|
||||||
|
ensure!(
|
||||||
|
store.compare_and_swap_batch(&[], vec![row.clone()])?,
|
||||||
|
"catalog store changed during initialization"
|
||||||
|
);
|
||||||
|
(row, state)
|
||||||
|
}
|
||||||
|
[row]
|
||||||
|
if row.r#type == STORE_TYPE
|
||||||
|
&& row.key == STORE_KEY
|
||||||
|
&& row.schema_id.as_deref() == Some(STORE_TYPE) =>
|
||||||
|
{
|
||||||
|
let state: CatalogState =
|
||||||
|
rmp_serde::from_slice(&row.payload).context("catalog state is corrupt")?;
|
||||||
|
ensure!(
|
||||||
|
rmp_serde::to_vec_named(&state)? == row.payload,
|
||||||
|
"catalog state is not canonical"
|
||||||
|
);
|
||||||
|
(row.clone(), state)
|
||||||
|
}
|
||||||
|
_ => bail!("catalog store contains foreign records"),
|
||||||
|
};
|
||||||
|
Ok(Self { store, row, state })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn validate_custody(&self) -> anyhow::Result<()> {
|
||||||
|
self.store
|
||||||
|
.validate_path_identity()
|
||||||
|
.context("catalog store path identity changed")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn commit(&mut self, next: CatalogState) -> anyhow::Result<()> {
|
||||||
|
let next_row = envelope(&next)?;
|
||||||
|
let swapped = self
|
||||||
|
.store
|
||||||
|
.compare_and_swap_batch(std::slice::from_ref(&self.row), vec![next_row.clone()]);
|
||||||
|
ensure!(
|
||||||
|
matches!(swapped, Ok(true)),
|
||||||
|
"catalog commit outcome is uncertain; sole ownership was lost"
|
||||||
|
);
|
||||||
|
self.row = next_row;
|
||||||
|
self.state = next;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The one function that makes a timeline. Begin passes the new world's
|
||||||
|
/// record beside its root timeline; a fork passes `None` and a parent. The
|
||||||
|
/// player's pointer moves to the new timeline in the same write.
|
||||||
|
pub(crate) fn mint_timeline(
|
||||||
|
&mut self,
|
||||||
|
new_world: Option<WorldRecord>,
|
||||||
|
timeline: Timeline,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
ensure!(
|
||||||
|
timeline_directory_name(&timeline.id).is_some(),
|
||||||
|
"timeline id is not canonical"
|
||||||
|
);
|
||||||
|
ensure!(
|
||||||
|
!self.state.timelines.contains_key(&timeline.id),
|
||||||
|
"timeline already exists"
|
||||||
|
);
|
||||||
|
let mut next = self.state.clone();
|
||||||
|
let owner = match new_world {
|
||||||
|
Some(record) => {
|
||||||
|
ensure!(
|
||||||
|
record.world_id == timeline.world_id && timeline.parent.is_none(),
|
||||||
|
"a new world's first timeline is its root"
|
||||||
|
);
|
||||||
|
ensure!(
|
||||||
|
!next.worlds.contains_key(&record.world_id),
|
||||||
|
"world record already exists"
|
||||||
|
);
|
||||||
|
let owner = record.owner.clone();
|
||||||
|
next.worlds.insert(record.world_id.clone(), record);
|
||||||
|
owner
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
let (parent, _) = timeline
|
||||||
|
.parent
|
||||||
|
.as_ref()
|
||||||
|
.context("a timeline in an existing world names its parent")?;
|
||||||
|
let parent = next.timelines.get(parent).context("parent timeline is unknown")?;
|
||||||
|
ensure!(parent.world_id == timeline.world_id, "fork crosses worlds");
|
||||||
|
next.worlds
|
||||||
|
.get(&timeline.world_id)
|
||||||
|
.context("world record is unknown")?
|
||||||
|
.owner
|
||||||
|
.clone()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let player = next
|
||||||
|
.players
|
||||||
|
.entry(owner.clone())
|
||||||
|
.or_insert_with(|| PlayerSession {
|
||||||
|
principal: owner,
|
||||||
|
timeline: None,
|
||||||
|
destination: None,
|
||||||
|
});
|
||||||
|
player.timeline = Some(timeline.id.clone());
|
||||||
|
next.timelines.insert(timeline.id.clone(), timeline);
|
||||||
|
self.commit(next)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Mints a single-use invite and returns its token, the only time it is
|
||||||
|
/// visible. The catalog keeps its hash and expiry.
|
||||||
|
pub(crate) fn mint_invite(&mut self, now: DateTime<Utc>, ttl: chrono::Duration) -> anyhow::Result<String> {
|
||||||
|
let token = format!("{}{}", Uuid::new_v4().simple(), Uuid::new_v4().simple());
|
||||||
|
let mut next = self.state.clone();
|
||||||
|
next.invites.retain(|_, expires| *expires > now);
|
||||||
|
next.invites.insert(token_hash(&token), now + ttl);
|
||||||
|
self.commit(next)?;
|
||||||
|
Ok(token)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `token` names an invite that is live at `now`. Read-only: it
|
||||||
|
/// spends nothing, so a begin can ask it before Heimdall is.
|
||||||
|
pub(crate) fn invite_is_live(&self, token: &str, now: DateTime<Utc>) -> bool {
|
||||||
|
self.hash_is_live(&token_hash(token), now)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hash_is_live(&self, hash: &str, now: DateTime<Utc>) -> bool {
|
||||||
|
self.state.invites.get(hash).is_some_and(|expires| *expires > now)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The account an authenticated external identity lands on. A known
|
||||||
|
/// identity reaches its account, on any device. An unknown one needs a
|
||||||
|
/// live invite, which is consumed in the same write that creates the
|
||||||
|
/// account and binds the identity. No account and no live invite: refused,
|
||||||
|
/// never enrolled. Returns the account's principal key, the identity the
|
||||||
|
/// account was first created from.
|
||||||
|
pub(crate) fn sign_in(
|
||||||
|
&mut self,
|
||||||
|
identity: &str,
|
||||||
|
invite: Option<&str>,
|
||||||
|
now: DateTime<Utc>,
|
||||||
|
) -> anyhow::Result<Result<String, SignInRefusal>> {
|
||||||
|
if let Some(account) = self.state.identities.get(identity) {
|
||||||
|
let account = &self.state.accounts[account];
|
||||||
|
return Ok(Ok(account.identities[0].clone()));
|
||||||
|
}
|
||||||
|
let Some(hash) = invite.map(token_hash).filter(|hash| self.hash_is_live(hash, now)) else {
|
||||||
|
return Ok(Err(SignInRefusal::NoInvite));
|
||||||
|
};
|
||||||
|
let mut next = self.state.clone();
|
||||||
|
next.invites.remove(&hash);
|
||||||
|
next.invites.retain(|_, expires| *expires > now);
|
||||||
|
let account_id = format!("account:{}", Uuid::new_v4());
|
||||||
|
next.identities.insert(identity.to_owned(), account_id.clone());
|
||||||
|
next.accounts.insert(
|
||||||
|
account_id.clone(),
|
||||||
|
Account {
|
||||||
|
account_id,
|
||||||
|
identities: vec![identity.to_owned()],
|
||||||
|
created_at: now,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
self.commit(next)?;
|
||||||
|
Ok(Ok(identity.to_owned()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Links a second external identity to the account `principal` names.
|
||||||
|
/// Test-only until a second-identity link is a designed feature.
|
||||||
|
#[cfg(test)]
|
||||||
|
pub(crate) fn link_identity(&mut self, principal: &str, identity: &str) -> anyhow::Result<()> {
|
||||||
|
let account_id = self.state.identities[principal].clone();
|
||||||
|
let mut next = self.state.clone();
|
||||||
|
next.identities.insert(identity.to_owned(), account_id.clone());
|
||||||
|
next.accounts.get_mut(&account_id).unwrap().identities.push(identity.to_owned());
|
||||||
|
self.commit(next)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn timeline(&self, id: &str) -> Option<&Timeline> {
|
||||||
|
self.state.timelines.get(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The seed status of a timeline, `None` when it is Ready.
|
||||||
|
pub(crate) fn seed_status(&self, timeline: &str) -> Option<&SeedStatus> {
|
||||||
|
self.state.seeds.get(timeline)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Claims the seed of `timeline`, durably; false when one is running.
|
||||||
|
pub(crate) fn claim_seed(&mut self, timeline: &str) -> anyhow::Result<bool> {
|
||||||
|
if self.state.seeds.get(timeline) == Some(&SeedStatus::Seeding) {
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
self.settle_seed(timeline, Some(SeedStatus::Seeding))?;
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Records where a seed stands; `None` is Ready.
|
||||||
|
pub(crate) fn settle_seed(&mut self, timeline: &str, status: Option<SeedStatus>) -> anyhow::Result<()> {
|
||||||
|
let mut next = self.state.clone();
|
||||||
|
match status {
|
||||||
|
Some(status) => next.seeds.insert(timeline.to_owned(), status),
|
||||||
|
None => next.seeds.remove(timeline),
|
||||||
|
};
|
||||||
|
self.commit(next)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Marks every seed still Seeding as Failed. A seed runs only inside the
|
||||||
|
/// process that claimed it, so one still Seeding at startup was cut off
|
||||||
|
/// by a restart. Returns how many.
|
||||||
|
pub(crate) fn fail_interrupted_seeds(&mut self) -> anyhow::Result<usize> {
|
||||||
|
let mut next = self.state.clone();
|
||||||
|
let mut count = 0;
|
||||||
|
for status in next.seeds.values_mut().filter(|status| **status == SeedStatus::Seeding) {
|
||||||
|
*status = SeedStatus::Failed("seeding was interrupted by a restart".into());
|
||||||
|
count += 1;
|
||||||
|
}
|
||||||
|
if count > 0 {
|
||||||
|
self.commit(next)?;
|
||||||
|
}
|
||||||
|
Ok(count)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn world(&self, world_id: &str) -> Option<&WorldRecord> {
|
||||||
|
self.state.worlds.get(world_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The timeline and its world, only if `principal` owns the world.
|
||||||
|
pub(crate) fn owned_timeline(
|
||||||
|
&self,
|
||||||
|
principal: &str,
|
||||||
|
id: &str,
|
||||||
|
) -> Option<(&Timeline, &WorldRecord)> {
|
||||||
|
let timeline = self.state.timelines.get(id)?;
|
||||||
|
let world = self.state.worlds.get(&timeline.world_id)?;
|
||||||
|
(world.owner == principal).then_some((timeline, world))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn timelines_of(&self, principal: &str) -> Vec<(&Timeline, &WorldRecord)> {
|
||||||
|
self.state
|
||||||
|
.timelines
|
||||||
|
.values()
|
||||||
|
.filter_map(|timeline| {
|
||||||
|
let world = self.state.worlds.get(&timeline.world_id)?;
|
||||||
|
(world.owner == principal).then_some((timeline, world))
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn player(&self, principal: &str) -> Option<&PlayerSession> {
|
||||||
|
self.state.players.get(principal)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Moves the player's pointer to a timeline they own.
|
||||||
|
pub(crate) fn set_current(&mut self, principal: &str, timeline: &str) -> anyhow::Result<()> {
|
||||||
|
ensure!(
|
||||||
|
self.owned_timeline(principal, timeline).is_some(),
|
||||||
|
"that timeline is not this player's"
|
||||||
|
);
|
||||||
|
let mut next = self.state.clone();
|
||||||
|
next.players
|
||||||
|
.entry(principal.to_owned())
|
||||||
|
.or_insert_with(|| PlayerSession {
|
||||||
|
principal: principal.to_owned(),
|
||||||
|
timeline: None,
|
||||||
|
destination: None,
|
||||||
|
})
|
||||||
|
.timeline = Some(timeline.to_owned());
|
||||||
|
self.commit(next)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn envelope(state: &CatalogState) -> anyhow::Result<CultCacheEnvelope> {
|
||||||
|
Ok(CultCacheEnvelope {
|
||||||
|
key: STORE_KEY.into(),
|
||||||
|
r#type: STORE_TYPE.into(),
|
||||||
|
payload: rmp_serde::to_vec_named(state)?,
|
||||||
|
stored_at: Utc::now().to_rfc3339(),
|
||||||
|
schema_id: Some(STORE_TYPE.into()),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn record(world: &str, owner: &str) -> WorldRecord {
|
||||||
|
WorldRecord {
|
||||||
|
world_id: world.into(),
|
||||||
|
title: "t".into(),
|
||||||
|
owner: owner.into(),
|
||||||
|
snapshot_id: Some("vault-snapshot:abc".into()),
|
||||||
|
created_at: Utc::now(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn root(world: &str) -> Timeline {
|
||||||
|
Timeline {
|
||||||
|
id: timeline_id(Uuid::new_v4()),
|
||||||
|
world_id: world.into(),
|
||||||
|
parent: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_timeline_id_is_a_directory_name_or_nothing() {
|
||||||
|
let good = timeline_id(Uuid::new_v4());
|
||||||
|
assert!(timeline_directory_name(&good).is_some());
|
||||||
|
for bad in [
|
||||||
|
"timeline:../../etc",
|
||||||
|
"timeline:",
|
||||||
|
"../timeline:00000000-0000-4000-8000-000000000000",
|
||||||
|
"timeline:00000000-0000-4000-8000-000000000000/..",
|
||||||
|
"timeline:00000000000040008000000000000000",
|
||||||
|
"timeline:00000000-0000-4000-8000-00000000000A",
|
||||||
|
] {
|
||||||
|
assert!(timeline_directory_name(bad).is_none(), "{bad}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_restart_reads_back_what_begin_wrote() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let path = directory.path().join("catalog.cc");
|
||||||
|
let line = root("w1");
|
||||||
|
{
|
||||||
|
let mut catalog = Catalog::open(&path).unwrap();
|
||||||
|
catalog.mint_timeline(Some(record("w1", "alice")), line.clone()).unwrap();
|
||||||
|
}
|
||||||
|
let catalog = Catalog::open(&path).unwrap();
|
||||||
|
assert_eq!(catalog.timeline(&line.id), Some(&line));
|
||||||
|
assert_eq!(catalog.world("w1").unwrap().snapshot_id.as_deref(), Some("vault-snapshot:abc"));
|
||||||
|
assert_eq!(catalog.player("alice").unwrap().timeline.as_deref(), Some(line.id.as_str()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_the_owner_reaches_a_timeline() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let mut catalog = Catalog::open(directory.path().join("catalog.cc")).unwrap();
|
||||||
|
let line = root("w1");
|
||||||
|
catalog.mint_timeline(Some(record("w1", "alice")), line.clone()).unwrap();
|
||||||
|
assert!(catalog.owned_timeline("alice", &line.id).is_some());
|
||||||
|
assert!(catalog.owned_timeline("mallory", &line.id).is_none());
|
||||||
|
assert!(catalog.timelines_of("mallory").is_empty());
|
||||||
|
assert!(catalog.set_current("mallory", &line.id).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// A seed's status is part of the catalog row: it survives a reopen, and a
|
||||||
|
/// seed still Seeding when the process starts again reads Failed, never
|
||||||
|
/// Ready.
|
||||||
|
#[test]
|
||||||
|
fn a_seed_status_persists_and_a_restart_fails_a_running_seed() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let path = directory.path().join("catalog.cc");
|
||||||
|
{
|
||||||
|
let mut catalog = Catalog::open(&path).unwrap();
|
||||||
|
assert!(catalog.claim_seed("timeline:a").unwrap());
|
||||||
|
assert!(!catalog.claim_seed("timeline:a").unwrap(), "one seed at a time");
|
||||||
|
catalog.settle_seed("timeline:b", Some(SeedStatus::Failed("no model".into()))).unwrap();
|
||||||
|
}
|
||||||
|
let mut catalog = Catalog::open(&path).unwrap();
|
||||||
|
assert_eq!(catalog.seed_status("timeline:a"), Some(&SeedStatus::Seeding));
|
||||||
|
assert_eq!(catalog.fail_interrupted_seeds().unwrap(), 1);
|
||||||
|
assert!(matches!(catalog.seed_status("timeline:a"), Some(SeedStatus::Failed(reason)) if reason.contains("restart")));
|
||||||
|
assert_eq!(catalog.seed_status("timeline:b"), Some(&SeedStatus::Failed("no model".into())));
|
||||||
|
assert_eq!(catalog.fail_interrupted_seeds().unwrap(), 0);
|
||||||
|
assert!(catalog.claim_seed("timeline:a").unwrap(), "a failed seed may be claimed again");
|
||||||
|
catalog.settle_seed("timeline:a", None).unwrap();
|
||||||
|
catalog.settle_seed("timeline:b", None).unwrap();
|
||||||
|
drop(catalog);
|
||||||
|
assert_eq!(Catalog::open(&path).unwrap().seed_status("timeline:a"), None);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn a_fork_is_minted_by_the_same_function_and_must_name_a_real_parent() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let mut catalog = Catalog::open(directory.path().join("catalog.cc")).unwrap();
|
||||||
|
let first = root("w1");
|
||||||
|
catalog.mint_timeline(Some(record("w1", "alice")), first.clone()).unwrap();
|
||||||
|
let fork = Timeline {
|
||||||
|
id: timeline_id(Uuid::new_v4()),
|
||||||
|
world_id: "w1".into(),
|
||||||
|
parent: Some((first.id.clone(), "commit-1".into())),
|
||||||
|
};
|
||||||
|
catalog.mint_timeline(None, fork.clone()).unwrap();
|
||||||
|
assert_eq!(catalog.player("alice").unwrap().timeline.as_deref(), Some(fork.id.as_str()));
|
||||||
|
let orphan = Timeline {
|
||||||
|
id: timeline_id(Uuid::new_v4()),
|
||||||
|
world_id: "w1".into(),
|
||||||
|
parent: Some(("timeline:00000000-0000-4000-8000-000000000000".into(), "c".into())),
|
||||||
|
};
|
||||||
|
assert!(catalog.mint_timeline(None, orphan).is_err());
|
||||||
|
assert!(catalog.mint_timeline(None, root("w1")).is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn token_hash(token: &str) -> String {
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
format!("{:x}", Sha256::digest(token.as_bytes()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod sign_in_tests {
|
||||||
|
use super::*;
|
||||||
|
use chrono::Duration;
|
||||||
|
|
||||||
|
fn catalog() -> (tempfile::TempDir, Catalog) {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let catalog = Catalog::open(directory.path().join("catalog.cc")).unwrap();
|
||||||
|
(directory, catalog)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_invite_is_single_use() {
|
||||||
|
let (_d, mut catalog) = catalog();
|
||||||
|
let now = Utc::now();
|
||||||
|
let token = catalog.mint_invite(now, Duration::hours(1)).unwrap();
|
||||||
|
assert!(catalog.sign_in("google:deru", Some(&token), now).unwrap().is_ok());
|
||||||
|
// The same invite for a second, different identity is spent.
|
||||||
|
assert_eq!(
|
||||||
|
catalog.sign_in("google:other", Some(&token), now).unwrap(),
|
||||||
|
Err(SignInRefusal::NoInvite)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_expired_invite_is_refused() {
|
||||||
|
let (_d, mut catalog) = catalog();
|
||||||
|
let now = Utc::now();
|
||||||
|
let token = catalog.mint_invite(now, Duration::hours(1)).unwrap();
|
||||||
|
let later = now + Duration::hours(2);
|
||||||
|
assert_eq!(
|
||||||
|
catalog.sign_in("google:deru", Some(&token), later).unwrap(),
|
||||||
|
Err(SignInRefusal::NoInvite)
|
||||||
|
);
|
||||||
|
assert!(catalog.state.accounts.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn no_account_and_no_invite_is_refused_and_enrols_nobody() {
|
||||||
|
let (_d, mut catalog) = catalog();
|
||||||
|
let now = Utc::now();
|
||||||
|
assert_eq!(catalog.sign_in("google:deru", None, now).unwrap(), Err(SignInRefusal::NoInvite));
|
||||||
|
assert_eq!(
|
||||||
|
catalog.sign_in("google:deru", Some("not-a-token"), now).unwrap(),
|
||||||
|
Err(SignInRefusal::NoInvite)
|
||||||
|
);
|
||||||
|
assert!(catalog.state.accounts.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_same_identity_on_a_second_device_lands_on_the_same_account_without_an_invite() {
|
||||||
|
let (directory, mut catalog) = catalog();
|
||||||
|
let now = Utc::now();
|
||||||
|
let token = catalog.mint_invite(now, Duration::hours(1)).unwrap();
|
||||||
|
let first = catalog.sign_in("google:deru", Some(&token), now).unwrap().unwrap();
|
||||||
|
let second = catalog.sign_in("google:deru", None, now).unwrap().unwrap();
|
||||||
|
assert_eq!(first, second);
|
||||||
|
assert_eq!(catalog.state.accounts.len(), 1);
|
||||||
|
// And it survives a restart.
|
||||||
|
drop(catalog);
|
||||||
|
let mut reopened = Catalog::open(directory.path().join("catalog.cc")).unwrap();
|
||||||
|
assert_eq!(reopened.sign_in("google:deru", None, now).unwrap().unwrap(), first);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_the_minted_token_redeems_its_invite_and_the_catalog_keeps_its_hash_alone() {
|
||||||
|
let (_d, mut catalog) = catalog();
|
||||||
|
let now = Utc::now();
|
||||||
|
let token = catalog.mint_invite(now, Duration::hours(1)).unwrap();
|
||||||
|
assert_eq!(token.len(), 64);
|
||||||
|
assert!(token.chars().all(|c| c.is_ascii_hexdigit()));
|
||||||
|
assert_ne!(token, catalog.mint_invite(now, Duration::hours(1)).unwrap());
|
||||||
|
for wrong in ["", "x", &token[1..], &format!("{token}0"), &token.to_uppercase()] {
|
||||||
|
assert_eq!(
|
||||||
|
catalog.sign_in("google:deru", Some(wrong), now).unwrap(),
|
||||||
|
Err(SignInRefusal::NoInvite),
|
||||||
|
"{wrong:?} must not redeem a live invite"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert!(catalog.state.invites.contains_key(&token_hash(&token)));
|
||||||
|
assert!(!catalog.state.invites.contains_key(&token), "the raw token is never stored");
|
||||||
|
assert!(catalog.sign_in("google:deru", Some(&token), now).unwrap().is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_token_hash_is_sha256_hex() {
|
||||||
|
assert_eq!(
|
||||||
|
token_hash("abc"),
|
||||||
|
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
|
||||||
|
);
|
||||||
|
assert_ne!(token_hash("abc"), token_hash("abd"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_invite_dies_at_its_expiry_instant_and_spent_or_dead_invites_are_pruned() {
|
||||||
|
let (_d, mut catalog) = catalog();
|
||||||
|
let now = Utc::now();
|
||||||
|
let short = catalog.mint_invite(now, Duration::hours(1)).unwrap();
|
||||||
|
let long = catalog.mint_invite(now, Duration::hours(3)).unwrap();
|
||||||
|
let at_expiry = now + Duration::hours(1);
|
||||||
|
assert_eq!(
|
||||||
|
catalog.sign_in("a", Some(&short), at_expiry).unwrap(),
|
||||||
|
Err(SignInRefusal::NoInvite),
|
||||||
|
"an invite is not live at the instant it expires"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
catalog.sign_in("a", Some(&short), at_expiry - Duration::seconds(1)).unwrap().is_ok(),
|
||||||
|
"and is live a second before"
|
||||||
|
);
|
||||||
|
assert_eq!(catalog.state.invites.len(), 1, "the spent invite is gone");
|
||||||
|
// Redeeming the long invite after the short one died prunes nothing live.
|
||||||
|
assert!(catalog.sign_in("b", Some(&long), at_expiry).unwrap().is_ok());
|
||||||
|
assert!(catalog.state.invites.is_empty());
|
||||||
|
// A mint prunes dead invites.
|
||||||
|
let stale = catalog.mint_invite(now, Duration::hours(1)).unwrap();
|
||||||
|
let later = now + Duration::hours(2);
|
||||||
|
let fresh = catalog.mint_invite(later, Duration::hours(1)).unwrap();
|
||||||
|
assert_eq!(catalog.state.invites.len(), 1);
|
||||||
|
assert!(!catalog.state.invites.contains_key(&token_hash(&stale)));
|
||||||
|
assert!(catalog.state.invites.contains_key(&token_hash(&fresh)));
|
||||||
|
assert_eq!(catalog.state.invites[&token_hash(&fresh)], later + Duration::hours(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_new_account_is_bound_to_its_identity_and_returns_it_as_the_principal() {
|
||||||
|
let (_d, mut catalog) = catalog();
|
||||||
|
let now = Utc::now();
|
||||||
|
let token = catalog.mint_invite(now, Duration::hours(1)).unwrap();
|
||||||
|
let principal = catalog.sign_in("google:deru", Some(&token), now).unwrap().unwrap();
|
||||||
|
assert_eq!(principal, "google:deru");
|
||||||
|
let account_id = &catalog.state.identities["google:deru"];
|
||||||
|
let account = &catalog.state.accounts[account_id];
|
||||||
|
assert_eq!(&account.account_id, account_id);
|
||||||
|
assert_eq!(account.identities, vec!["google:deru".to_owned()]);
|
||||||
|
assert_eq!(account.created_at, now);
|
||||||
|
assert!(account_id.starts_with("account:"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn mint_and_redemption_drop_invites_dead_at_that_very_instant() {
|
||||||
|
let (_d, mut catalog) = catalog();
|
||||||
|
let now = Utc::now();
|
||||||
|
let dying = catalog.mint_invite(now, Duration::hours(1)).unwrap();
|
||||||
|
let at = now + Duration::hours(1);
|
||||||
|
let minted = catalog.mint_invite(at, Duration::hours(1)).unwrap();
|
||||||
|
assert!(!catalog.state.invites.contains_key(&token_hash(&dying)), "mint prunes at the instant");
|
||||||
|
let dying = catalog.mint_invite(at, Duration::hours(1) - Duration::seconds(1)).unwrap();
|
||||||
|
let later = at + Duration::hours(1) - Duration::seconds(1);
|
||||||
|
assert!(catalog.sign_in("a", Some(&minted), later).unwrap().is_ok());
|
||||||
|
assert!(
|
||||||
|
!catalog.state.invites.contains_key(&token_hash(&dying)),
|
||||||
|
"redemption prunes an invite that expires at that instant"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_store_holding_a_row_of_the_wrong_type_key_or_schema_is_refused() {
|
||||||
|
for (row_type, key, schema) in [
|
||||||
|
("ghostlight.other.v1", STORE_KEY, STORE_TYPE),
|
||||||
|
(STORE_TYPE, "secondary", STORE_TYPE),
|
||||||
|
(STORE_TYPE, STORE_KEY, "ghostlight.other.v1"),
|
||||||
|
] {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let path = directory.path().join("catalog.cc");
|
||||||
|
let store = OwnedRedbMessagePackBackingStore::new(&path).unwrap();
|
||||||
|
let mut row = envelope(&CatalogState::default()).unwrap();
|
||||||
|
row.r#type = row_type.into();
|
||||||
|
row.key = key.into();
|
||||||
|
row.schema_id = Some(schema.into());
|
||||||
|
assert!(store.compare_and_swap_batch(&[], vec![row]).unwrap());
|
||||||
|
drop(store);
|
||||||
|
assert!(Catalog::open(&path).is_err(), "{row_type} {key} {schema}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn custody_fails_once_the_store_path_is_replaced() {
|
||||||
|
let (directory, catalog) = catalog();
|
||||||
|
catalog.validate_custody().unwrap();
|
||||||
|
let path = directory.path().join("catalog.cc");
|
||||||
|
std::fs::rename(&path, directory.path().join("displaced.cc")).unwrap();
|
||||||
|
std::fs::File::create(&path).unwrap();
|
||||||
|
assert!(catalog.validate_custody().is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
1842
crates/ghostlight-dungeon/src/heimdall.rs
Normal file
1970
crates/ghostlight-dungeon/src/idunn_health.rs
Normal file
211
crates/ghostlight-dungeon/src/invite.rs
Normal file
|
|
@ -0,0 +1,211 @@
|
||||||
|
//! The operator's invite mint.
|
||||||
|
//!
|
||||||
|
//! Invites are minted on a Unix domain socket owned by the service user, mode
|
||||||
|
//! 0600, under the state root. The HTTP router has no invite path, so the
|
||||||
|
//! reverse proxy has nothing to forward: reaching the mint takes a local
|
||||||
|
//! process running as the service user, not a peer-address test.
|
||||||
|
//!
|
||||||
|
//! Wire: the client writes one line, the number of hours. The daemon answers
|
||||||
|
//! one JSON line, `{"invite": "<token>"}` or `{"error": "<why>"}`.
|
||||||
|
|
||||||
|
use crate::catalog::Catalog;
|
||||||
|
use anyhow::{Context, bail, ensure};
|
||||||
|
use chrono::Utc;
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
use std::{
|
||||||
|
os::unix::{
|
||||||
|
fs::{FileTypeExt, PermissionsExt},
|
||||||
|
net::UnixStream as StdUnixStream,
|
||||||
|
},
|
||||||
|
path::{Path, PathBuf},
|
||||||
|
sync::Arc,
|
||||||
|
};
|
||||||
|
use tokio::{
|
||||||
|
io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader},
|
||||||
|
net::{UnixListener, UnixStream},
|
||||||
|
sync::Mutex,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// An invite lives between one hour and thirty days.
|
||||||
|
const MAX_HOURS: u32 = 24 * 30;
|
||||||
|
const REQUEST_LIMIT: u64 = 32;
|
||||||
|
|
||||||
|
pub(crate) fn socket_path(runtime_root: &Path) -> PathBuf {
|
||||||
|
runtime_root.join("service").join("invite.sock")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Binds the mint socket, replacing a stale socket left by a previous run and
|
||||||
|
/// refusing anything else at the path. The socket is created under a 0177 umask
|
||||||
|
/// so it is never visible with wider permissions.
|
||||||
|
pub(crate) fn bind(path: &Path) -> anyhow::Result<UnixListener> {
|
||||||
|
match std::fs::symlink_metadata(path) {
|
||||||
|
Ok(metadata) => {
|
||||||
|
ensure!(
|
||||||
|
metadata.file_type().is_socket(),
|
||||||
|
"{} exists and is not a socket",
|
||||||
|
path.display()
|
||||||
|
);
|
||||||
|
std::fs::remove_file(path).context("removing a stale invite socket")?;
|
||||||
|
}
|
||||||
|
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
|
||||||
|
Err(error) => return Err(error).context("inspecting the invite socket path"),
|
||||||
|
}
|
||||||
|
// SAFETY: umask only swaps the process file-creation mask.
|
||||||
|
let previous = unsafe { libc::umask(0o177) };
|
||||||
|
let bound = UnixListener::bind(path);
|
||||||
|
unsafe { libc::umask(previous) };
|
||||||
|
let listener = bound.with_context(|| format!("binding {}", path.display()))?;
|
||||||
|
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?;
|
||||||
|
Ok(listener)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn serve(listener: UnixListener, catalog: Arc<Mutex<Catalog>>) -> anyhow::Result<()> {
|
||||||
|
loop {
|
||||||
|
let (stream, _) = listener.accept().await.context("accepting on the invite socket")?;
|
||||||
|
let catalog = catalog.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
if let Err(error) = answer(stream, &catalog).await {
|
||||||
|
tracing::warn!(%error, "an invite request failed");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn answer(stream: UnixStream, catalog: &Mutex<Catalog>) -> anyhow::Result<()> {
|
||||||
|
let (read, mut write) = stream.into_split();
|
||||||
|
let mut line = String::new();
|
||||||
|
BufReader::new(read.take(REQUEST_LIMIT)).read_line(&mut line).await?;
|
||||||
|
let reply = match mint(catalog, line.trim()).await {
|
||||||
|
Ok(token) => json!({"invite": token}),
|
||||||
|
Err(message) => json!({"error": message}),
|
||||||
|
};
|
||||||
|
write.write_all(format!("{reply}\n").as_bytes()).await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn mint(catalog: &Mutex<Catalog>, hours: &str) -> Result<String, String> {
|
||||||
|
let hours: u32 = hours
|
||||||
|
.parse()
|
||||||
|
.map_err(|_| "the request is a whole number of hours".to_owned())?;
|
||||||
|
if hours == 0 || hours > MAX_HOURS {
|
||||||
|
return Err("an invite lives between 1 hour and 30 days".into());
|
||||||
|
}
|
||||||
|
catalog
|
||||||
|
.lock()
|
||||||
|
.await
|
||||||
|
.mint_invite(Utc::now(), chrono::Duration::hours(i64::from(hours)))
|
||||||
|
.map_err(|error| {
|
||||||
|
tracing::error!(%error, "an invite could not be minted");
|
||||||
|
"the invite could not be minted".to_owned()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The operator command: asks the running daemon at `runtime_root` for an invite.
|
||||||
|
pub(crate) fn request(runtime_root: &Path, hours: u32) -> anyhow::Result<String> {
|
||||||
|
use std::io::{BufRead, Write};
|
||||||
|
let path = socket_path(runtime_root);
|
||||||
|
let mut stream = StdUnixStream::connect(&path)
|
||||||
|
.with_context(|| format!("no daemon is listening at {}", path.display()))?;
|
||||||
|
writeln!(stream, "{hours}")?;
|
||||||
|
let mut reply = String::new();
|
||||||
|
std::io::BufReader::new(stream).read_line(&mut reply)?;
|
||||||
|
let reply: Value = serde_json::from_str(&reply).context("the daemon's answer is not JSON")?;
|
||||||
|
match (reply["invite"].as_str(), reply["error"].as_str()) {
|
||||||
|
(Some(token), _) => Ok(token.to_owned()),
|
||||||
|
(None, Some(error)) => bail!("{error}"),
|
||||||
|
(None, None) => bail!("the daemon's answer names neither an invite nor an error"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use std::os::unix::fs::MetadataExt;
|
||||||
|
|
||||||
|
fn catalog(directory: &Path) -> Arc<Mutex<Catalog>> {
|
||||||
|
Arc::new(Mutex::new(Catalog::open(directory.join("catalog.cc")).unwrap()))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn serving(root: &Path) -> Arc<Mutex<Catalog>> {
|
||||||
|
std::fs::create_dir_all(root.join("service")).unwrap();
|
||||||
|
let catalog = catalog(root);
|
||||||
|
let listener = bind(&socket_path(root)).unwrap();
|
||||||
|
tokio::spawn(serve(listener, catalog.clone()));
|
||||||
|
catalog
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn ask(root: &Path, hours: u32) -> anyhow::Result<String> {
|
||||||
|
let root = root.to_owned();
|
||||||
|
tokio::task::spawn_blocking(move || request(&root, hours)).await.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn the_socket_is_private_and_its_token_enrols_exactly_once() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let catalog = serving(directory.path()).await;
|
||||||
|
let mode = std::fs::metadata(socket_path(directory.path())).unwrap().mode();
|
||||||
|
assert_eq!(mode & 0o777, 0o600, "mode {mode:o}");
|
||||||
|
let token = ask(directory.path(), 2).await.unwrap();
|
||||||
|
let mut catalog = catalog.lock().await;
|
||||||
|
assert!(catalog.sign_in("google:deru", Some(&token), Utc::now()).unwrap().is_ok());
|
||||||
|
assert!(catalog.sign_in("google:other", Some(&token), Utc::now()).unwrap().is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn an_invite_lives_one_hour_to_thirty_days_and_expires_at_its_hours() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let catalog = serving(directory.path()).await;
|
||||||
|
for hours in [0, 24 * 30 + 1] {
|
||||||
|
let error = ask(directory.path(), hours).await.unwrap_err();
|
||||||
|
assert!(error.to_string().contains("between 1 hour and 30 days"), "{hours}: {error}");
|
||||||
|
}
|
||||||
|
let longest = ask(directory.path(), 24 * 30).await.unwrap();
|
||||||
|
let shortest = ask(directory.path(), 1).await.unwrap();
|
||||||
|
let mut catalog = catalog.lock().await;
|
||||||
|
let in_two_hours = Utc::now() + chrono::Duration::hours(2);
|
||||||
|
assert!(catalog.sign_in("a", Some(&shortest), in_two_hours).unwrap().is_err());
|
||||||
|
let in_thirty_days = Utc::now() + chrono::Duration::days(30) - chrono::Duration::minutes(1);
|
||||||
|
assert!(catalog.sign_in("b", Some(&longest), in_thirty_days).unwrap().is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn binding_replaces_a_stale_socket_and_refuses_a_regular_file() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let path = directory.path().join("invite.sock");
|
||||||
|
drop(bind(&path).unwrap());
|
||||||
|
assert!(path.exists(), "the dropped listener leaves its socket file");
|
||||||
|
drop(bind(&path).unwrap());
|
||||||
|
std::fs::remove_file(&path).unwrap();
|
||||||
|
std::fs::write(&path, "not a socket").unwrap();
|
||||||
|
assert!(bind(&path).is_err());
|
||||||
|
assert_eq!(std::fs::read_to_string(&path).unwrap(), "not a socket");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_request_that_is_not_hours_mints_nothing() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let catalog = serving(directory.path()).await;
|
||||||
|
let root = directory.path().to_owned();
|
||||||
|
let reply = tokio::task::spawn_blocking(move || {
|
||||||
|
use std::io::{Read, Write};
|
||||||
|
let mut stream = StdUnixStream::connect(socket_path(&root)).unwrap();
|
||||||
|
writeln!(stream, "soon").unwrap();
|
||||||
|
let mut reply = String::new();
|
||||||
|
stream.read_to_string(&mut reply).unwrap();
|
||||||
|
reply
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert!(reply.contains("error"), "{reply}");
|
||||||
|
assert!(catalog.lock().await.sign_in("x", Some("anything"), Utc::now()).unwrap().is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_socket_path_that_cannot_be_inspected_is_an_error_not_a_free_path() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let file = directory.path().join("file");
|
||||||
|
std::fs::write(&file, "x").unwrap();
|
||||||
|
let error = bind(&file.join("invite.sock")).unwrap_err();
|
||||||
|
assert!(format!("{error:#}").contains("inspecting the invite socket path"), "{error:#}");
|
||||||
|
}
|
||||||
|
}
|
||||||
40
crates/ghostlight-dungeon/src/main.rs
Normal file
|
|
@ -0,0 +1,40 @@
|
||||||
|
mod api;
|
||||||
|
mod app_session;
|
||||||
|
mod auth_guard;
|
||||||
|
mod begin;
|
||||||
|
mod catalog;
|
||||||
|
mod heimdall;
|
||||||
|
mod idunn_health;
|
||||||
|
mod invite;
|
||||||
|
mod page;
|
||||||
|
mod play;
|
||||||
|
mod run_ahead;
|
||||||
|
mod runtime;
|
||||||
|
mod session_refresh;
|
||||||
|
mod state_layout;
|
||||||
|
mod timelines;
|
||||||
|
mod turn_log;
|
||||||
|
mod vaults;
|
||||||
|
|
||||||
|
use anyhow::bail;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> anyhow::Result<()> {
|
||||||
|
let args = std::env::args_os().skip(1).collect::<Vec<_>>();
|
||||||
|
let state_root = match args.as_slice() {
|
||||||
|
[command, flag, path, hours] if command == "invite" && flag == "--state-root" => {
|
||||||
|
let hours = hours.to_string_lossy().parse::<u32>()?;
|
||||||
|
println!("{}", invite::request(&PathBuf::from(path), hours)?);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
[command, flag, path, profile] if command == "import-vault" && flag == "--state-root" => {
|
||||||
|
println!("{}", vaults::import(&PathBuf::from(path), &profile.to_string_lossy())?);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
[flag, path] if flag == "--state-root" => Some(PathBuf::from(path)),
|
||||||
|
[] => None,
|
||||||
|
_ => bail!("usage: ghostlight-dungeon [--state-root PATH] | ghostlight-dungeon invite --state-root PATH HOURS | ghostlight-dungeon import-vault --state-root PATH PROFILE"),
|
||||||
|
};
|
||||||
|
runtime::run(state_root).await
|
||||||
|
}
|
||||||
44
crates/ghostlight-dungeon/src/page.rs
Normal file
|
|
@ -0,0 +1,44 @@
|
||||||
|
//! The play page: three static files compiled into the binary and served from
|
||||||
|
//! the router's root. They hold presentation only and no secret, so there is
|
||||||
|
//! no page directory to resolve at run time and nothing to drift from the
|
||||||
|
//! binary.
|
||||||
|
|
||||||
|
use crate::runtime::AppState;
|
||||||
|
use axum::{
|
||||||
|
Router,
|
||||||
|
http::{HeaderValue, StatusCode, header},
|
||||||
|
response::{IntoResponse, Response},
|
||||||
|
routing::get,
|
||||||
|
};
|
||||||
|
|
||||||
|
const INDEX: &str = include_str!("../page/index.html");
|
||||||
|
const STYLE: &str = include_str!("../page/page.css");
|
||||||
|
const SCRIPT: &str = include_str!("../page/page.js");
|
||||||
|
|
||||||
|
/// The page loads only its own script and style and talks only to its own
|
||||||
|
/// origin, so injected markup has nowhere to run or to send anything.
|
||||||
|
const POLICY: &str = "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; \
|
||||||
|
img-src 'self' data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'";
|
||||||
|
|
||||||
|
fn file(content_type: &'static str, body: &'static str) -> Response {
|
||||||
|
(
|
||||||
|
StatusCode::OK,
|
||||||
|
[
|
||||||
|
(header::CONTENT_TYPE, HeaderValue::from_static(content_type)),
|
||||||
|
(header::CACHE_CONTROL, HeaderValue::from_static("no-cache")),
|
||||||
|
(header::CONTENT_SECURITY_POLICY, HeaderValue::from_static(POLICY)),
|
||||||
|
(header::X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")),
|
||||||
|
(header::REFERRER_POLICY, HeaderValue::from_static("no-referrer")),
|
||||||
|
(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY")),
|
||||||
|
],
|
||||||
|
body,
|
||||||
|
)
|
||||||
|
.into_response()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn router() -> Router<AppState> {
|
||||||
|
Router::new()
|
||||||
|
.route("/", get(|| async { file("text/html; charset=utf-8", INDEX) }))
|
||||||
|
.route("/page.css", get(|| async { file("text/css; charset=utf-8", STYLE) }))
|
||||||
|
.route("/page.js", get(|| async { file("text/javascript; charset=utf-8", SCRIPT) }))
|
||||||
|
}
|
||||||
12035
crates/ghostlight-dungeon/src/play.rs
Normal file
108
crates/ghostlight-dungeon/src/run_ahead.rs
Normal file
|
|
@ -0,0 +1,108 @@
|
||||||
|
//! Run-ahead: the bounded Active elaboration sweep.
|
||||||
|
//!
|
||||||
|
//! A world's scale deficit is answered after play starts, not before: one sweep
|
||||||
|
//! once Begin activates a seeded world, and one after each closed turn. Each
|
||||||
|
//! sweep starts at most `Scale::sweep_sessions` elaboration sessions and holds
|
||||||
|
//! at most `Scale::sweep_permits` permits, so a trigger cannot spend without
|
||||||
|
//! bound. The elaborator reads the evidence of the snapshot its timeline is
|
||||||
|
//! bound to, the same evidence the seed read; an unseeded world reads none.
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
begin::{Scale, Vaults},
|
||||||
|
catalog::Catalog,
|
||||||
|
timelines::TimelineHost,
|
||||||
|
};
|
||||||
|
use ghostlight::{EvidenceSource, NullEvidenceSource};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use tokio::sync::{Mutex, Semaphore};
|
||||||
|
|
||||||
|
/// One bounded sweep of `host` over `evidence`. A sweep already running on this
|
||||||
|
/// timeline is the trigger's answer: the sweep that follows picks up what this
|
||||||
|
/// one would have.
|
||||||
|
pub(crate) async fn run_ahead(host: &TimelineHost, evidence: Arc<dyn EvidenceSource>, scale: &Scale) {
|
||||||
|
let Ok(_running) = host.sweeping.try_lock() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let runner = host.controllers.elaborator(evidence);
|
||||||
|
let permits = Arc::new(Semaphore::new(scale.sweep_permits));
|
||||||
|
if let Err(error) = runner.sweep(permits, scale.sweep_sessions).await {
|
||||||
|
tracing::warn!(%error, "run-ahead elaboration stopped");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The evidence a timeline's elaborator reads: its bound snapshot's, for the
|
||||||
|
/// era its world was pinned to, or none for a world that began unseeded. A
|
||||||
|
/// bound snapshot that cannot be reopened, or a world that cannot be read,
|
||||||
|
/// yields no evidence at all and no sweep, never a blind or era-blind one.
|
||||||
|
pub(crate) async fn evidence_of(
|
||||||
|
catalog: &Mutex<Catalog>,
|
||||||
|
vaults: &dyn Vaults,
|
||||||
|
host: &TimelineHost,
|
||||||
|
timeline: &str,
|
||||||
|
) -> Option<Arc<dyn EvidenceSource>> {
|
||||||
|
let snapshot_id = {
|
||||||
|
let catalog = catalog.lock().await;
|
||||||
|
let world = catalog.world(&catalog.timeline(timeline)?.world_id)?;
|
||||||
|
world.snapshot_id.clone()
|
||||||
|
};
|
||||||
|
let Some(id) = snapshot_id else {
|
||||||
|
return Some(Arc::new(NullEvidenceSource));
|
||||||
|
};
|
||||||
|
let era = host.world.snapshot().await.ok()?.era;
|
||||||
|
match vaults.evidence(&id, era.as_ref().map(|era| era.id.as_str())) {
|
||||||
|
Ok(evidence) => Some(evidence),
|
||||||
|
Err(error) => {
|
||||||
|
tracing::warn!(%error, timeline, "a seeded timeline's snapshot could not be reopened");
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::{
|
||||||
|
begin::{
|
||||||
|
BeginRequest, begin,
|
||||||
|
tests::{NoVaults, deferred_rig, one_vault, principal, request},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
/// A timeline's elaborator reads what its world was bound to: nothing
|
||||||
|
/// for an unseeded world, the snapshot for a seeded one, and no evidence
|
||||||
|
/// (so no sweep) for a snapshot that cannot be reopened or a timeline the
|
||||||
|
/// catalog does not know.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn the_evidence_of_a_timeline_is_its_bound_snapshots() {
|
||||||
|
let vaults = one_vault();
|
||||||
|
let rig = deferred_rig();
|
||||||
|
let alice = principal("alice");
|
||||||
|
let unseeded = begin(&rig.catalog, &rig.timelines, &NoVaults, &rig.scale, &alice, request(Uuid::new_v4(), None))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let host = rig.timelines.host(&unseeded.timeline).await.unwrap();
|
||||||
|
assert!(
|
||||||
|
evidence_of(&rig.catalog, &NoVaults, &host, &unseeded.timeline).await.is_some(),
|
||||||
|
"an unseeded world reads none, and still sweeps"
|
||||||
|
);
|
||||||
|
let seeded = begin(
|
||||||
|
&rig.catalog,
|
||||||
|
&rig.timelines,
|
||||||
|
vaults.as_ref(),
|
||||||
|
&rig.scale,
|
||||||
|
&alice,
|
||||||
|
BeginRequest { era: Some("b".into()), ..request(Uuid::new_v4(), Some("delvehold")) },
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let host = rig.timelines.host(&seeded.timeline).await.unwrap();
|
||||||
|
assert!(evidence_of(&rig.catalog, vaults.as_ref(), &host, &seeded.timeline).await.is_some());
|
||||||
|
assert!(
|
||||||
|
evidence_of(&rig.catalog, &NoVaults, &host, &seeded.timeline).await.is_none(),
|
||||||
|
"an unreadable snapshot is never swept blind"
|
||||||
|
);
|
||||||
|
let stranger = "timeline:00000000-0000-4000-8000-000000000000";
|
||||||
|
assert!(evidence_of(&rig.catalog, vaults.as_ref(), &host, stranger).await.is_none());
|
||||||
|
}
|
||||||
|
}
|
||||||
872
crates/ghostlight-dungeon/src/runtime.rs
Normal file
|
|
@ -0,0 +1,872 @@
|
||||||
|
//! One-process runtime: admission, shared inference, the catalog and the
|
||||||
|
//! timeline registry, served over one router.
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
api,
|
||||||
|
app_session::AppSessionOwner,
|
||||||
|
auth_guard::AuthGuard,
|
||||||
|
begin::{Scale, Vaults},
|
||||||
|
catalog::Catalog,
|
||||||
|
heimdall::{HeimdallClient, HeimdallPort},
|
||||||
|
idunn_health::{
|
||||||
|
IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT, ProcessWriteLeaseGuard, RuntimePresencePublisher,
|
||||||
|
TARGET as GHOSTLIGHT_TARGET,
|
||||||
|
},
|
||||||
|
session_refresh::run_refresh_loop,
|
||||||
|
state_layout::{admitted_runtime_root, prepare_admitted_state_layout},
|
||||||
|
timelines::{Shared, Timelines},
|
||||||
|
};
|
||||||
|
use anyhow::{Context, bail, ensure};
|
||||||
|
use axum::{
|
||||||
|
Json, Router,
|
||||||
|
body::Bytes,
|
||||||
|
extract::{ConnectInfo, DefaultBodyLimit, State},
|
||||||
|
http::{HeaderMap, HeaderValue, StatusCode, header},
|
||||||
|
response::{IntoResponse, Response},
|
||||||
|
routing::{get, post},
|
||||||
|
};
|
||||||
|
use chrono::Utc;
|
||||||
|
use cultnet_rs::{
|
||||||
|
CultNetMessage, CultNetWireContract, GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA,
|
||||||
|
decode_cultnet_message_from_slice, encode_cultnet_message_to_vec,
|
||||||
|
};
|
||||||
|
use ghostlight::{
|
||||||
|
ConnectorBinding, ControllerModels, ControllerWorkCustody, InferencePort, open_inference,
|
||||||
|
};
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
use std::{
|
||||||
|
fs,
|
||||||
|
net::SocketAddr,
|
||||||
|
path::PathBuf,
|
||||||
|
sync::Arc,
|
||||||
|
time::{Duration, Instant},
|
||||||
|
};
|
||||||
|
use tokio::sync::{Mutex, Semaphore, mpsc};
|
||||||
|
use tracing_subscriber::EnvFilter;
|
||||||
|
|
||||||
|
const CULTNET_SNAPSHOT_BODY_LIMIT: usize = 16 * 1024;
|
||||||
|
const PROXY_HEADERS: [&str; 5] = [
|
||||||
|
"x-real-ip",
|
||||||
|
"x-forwarded-for",
|
||||||
|
"x-forwarded-host",
|
||||||
|
"x-forwarded-proto",
|
||||||
|
"forwarded",
|
||||||
|
];
|
||||||
|
const CONNECTOR_ADDRESS_ENVIRONMENT: &str = "GHOSTLIGHT_CONNECTOR_ADDR";
|
||||||
|
/// The credential path Idunn hands the workload: the operator binding's
|
||||||
|
/// `[workload.secret_files]` entry of this name becomes a systemd credential
|
||||||
|
/// and this variable holds the path of the loaded file, never its bytes.
|
||||||
|
const CONNECTOR_KEY_FILE_ENVIRONMENT: &str = "GHOSTLIGHT_CONNECTOR_KEY_FILE";
|
||||||
|
const CONNECTOR_CALLER: &str = "ghostlight";
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub(crate) struct RuntimeHealthOwner {
|
||||||
|
publisher: Arc<Mutex<RuntimePresencePublisher>>,
|
||||||
|
write_lease: Arc<ProcessWriteLeaseGuard>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub(crate) struct AppState {
|
||||||
|
pub(crate) catalog: Arc<Mutex<Catalog>>,
|
||||||
|
pub(crate) timelines: Arc<Timelines>,
|
||||||
|
pub(crate) vaults: Arc<dyn Vaults>,
|
||||||
|
pub(crate) scale: Arc<Scale>,
|
||||||
|
pub(crate) sessions: Arc<Mutex<AppSessionOwner>>,
|
||||||
|
pub(crate) heimdall: Arc<dyn HeimdallPort>,
|
||||||
|
pub(crate) auth: Arc<AuthGuard>,
|
||||||
|
pub(crate) runtime_id: String,
|
||||||
|
pub(crate) runtime_health: Option<RuntimeHealthOwner>,
|
||||||
|
pub(crate) fatal: mpsc::UnboundedSender<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ProductionAdmission {
|
||||||
|
health: RuntimePresencePublisher,
|
||||||
|
write_lease: ProcessWriteLeaseGuard,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The connector binding the Dungeon opens its one inference port with. Only
|
||||||
|
/// the path of the key's credential file is read here; the one connector port
|
||||||
|
/// opens the file.
|
||||||
|
fn connector_binding() -> anyhow::Result<ConnectorBinding> {
|
||||||
|
let endpoint = std::env::var(CONNECTOR_ADDRESS_ENVIRONMENT)
|
||||||
|
.with_context(|| format!("{CONNECTOR_ADDRESS_ENVIRONMENT} is required"))?
|
||||||
|
.parse()
|
||||||
|
.with_context(|| format!("{CONNECTOR_ADDRESS_ENVIRONMENT} is not a socket address"))?;
|
||||||
|
let key_path = std::env::var_os(CONNECTOR_KEY_FILE_ENVIRONMENT)
|
||||||
|
.map(PathBuf::from)
|
||||||
|
.with_context(|| format!("{CONNECTOR_KEY_FILE_ENVIRONMENT} is required"))?;
|
||||||
|
ensure!(
|
||||||
|
key_path.is_absolute(),
|
||||||
|
"{CONNECTOR_KEY_FILE_ENVIRONMENT} is not an absolute path"
|
||||||
|
);
|
||||||
|
Ok(ConnectorBinding {
|
||||||
|
endpoint,
|
||||||
|
key_path,
|
||||||
|
caller_runtime_id: CONNECTOR_CALLER.into(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The model each lane runs on, from env over the defaults the rulings set
|
||||||
|
/// (dungeon-model-per-role-answer): Opus for the narrator (the projector) and
|
||||||
|
/// the NPC Personas, Sonnet for the play table and the elaborator (which also
|
||||||
|
/// seeds), Haiku for the interpreter and the operational agent.
|
||||||
|
fn lane_models() -> (ControllerModels, String) {
|
||||||
|
lane_models_from(|name| std::env::var(name).ok())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lane_models_from(read: impl Fn(&str) -> Option<String>) -> (ControllerModels, String) {
|
||||||
|
let lane = |name: &str, default: &str| read(name).unwrap_or_else(|| default.into());
|
||||||
|
(
|
||||||
|
ControllerModels {
|
||||||
|
projector: lane("GHOSTLIGHT_CONTROLLER_PROJECTOR_MODEL", "claude-opus-5-5"),
|
||||||
|
persona: lane("GHOSTLIGHT_CONTROLLER_PERSONA_MODEL", "claude-opus-5-5"),
|
||||||
|
interpreter: lane("GHOSTLIGHT_CONTROLLER_INTERPRETER_MODEL", "claude-haiku-5-5"),
|
||||||
|
operational_agent: lane("GHOSTLIGHT_CONTROLLER_OPERATIONAL_MODEL", "claude-haiku-5-5"),
|
||||||
|
elaborator: lane("GHOSTLIGHT_CONTROLLER_ELABORATOR_MODEL", "claude-sonnet-5-5"),
|
||||||
|
},
|
||||||
|
lane("GHOSTLIGHT_PLAY_MODEL", "claude-sonnet-5-5"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The one routed inference port every timeline and lane shares.
|
||||||
|
fn open_shared() -> anyhow::Result<Shared> {
|
||||||
|
let (models, play_model) = lane_models();
|
||||||
|
let mut all: Vec<&str> = models.each().to_vec();
|
||||||
|
all.push(&play_model);
|
||||||
|
let inference: Arc<dyn InferencePort> =
|
||||||
|
open_inference(Some(connector_binding()?), None, None, None, &all)?;
|
||||||
|
Ok(Shared {
|
||||||
|
inference,
|
||||||
|
models,
|
||||||
|
play_model,
|
||||||
|
permits: Arc::new(Semaphore::new(configured_controller_concurrency())),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sized to the connector's per-caller quota. `Capacity` and `InFlight`
|
||||||
|
/// refusals are retryable faults, so a pool above that quota degrades to retry.
|
||||||
|
fn configured_controller_concurrency() -> usize {
|
||||||
|
std::env::var("GHOSTLIGHT_CONTROLLER_MAX_CONCURRENT")
|
||||||
|
.ok()
|
||||||
|
.and_then(|value| value.trim().parse::<usize>().ok())
|
||||||
|
.filter(|value| *value >= 1)
|
||||||
|
.unwrap_or(4)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn service_router(state: AppState) -> Router {
|
||||||
|
Router::new()
|
||||||
|
.route("/health", get(health))
|
||||||
|
.route(
|
||||||
|
"/cultnet/snapshot",
|
||||||
|
post(cultnet_snapshot).layer(DefaultBodyLimit::max(CULTNET_SNAPSHOT_BODY_LIMIT)),
|
||||||
|
)
|
||||||
|
.merge(api::router())
|
||||||
|
.merge(crate::page::router())
|
||||||
|
.with_state(state)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn run(state_root_binding: Option<PathBuf>) -> anyhow::Result<()> {
|
||||||
|
tracing_subscriber::fmt()
|
||||||
|
.with_env_filter(EnvFilter::from_default_env())
|
||||||
|
.init();
|
||||||
|
let runtime_root = admitted_runtime_root(state_root_binding)?;
|
||||||
|
let service_root = runtime_root.join("service");
|
||||||
|
// The bound socket is service observation, not configuration. Retain it
|
||||||
|
// unopened to application traffic while Warming waits for Idunn's lease.
|
||||||
|
let requested_address = candidate_bind()?;
|
||||||
|
let listener = tokio::net::TcpListener::bind(requested_address).await?;
|
||||||
|
let bound_address = listener.local_addr()?;
|
||||||
|
let (fatal, mut fatal_events) = mpsc::unbounded_channel();
|
||||||
|
let production_admission = initialize_production_admission(bound_address).await?;
|
||||||
|
let dependency_bindings = production_admission
|
||||||
|
.as_ref()
|
||||||
|
.map(|admission| admission.health.dependency_bindings().clone());
|
||||||
|
let runtime_id = match &production_admission {
|
||||||
|
Some(admission) => admission.health.runtime_id().to_owned(),
|
||||||
|
None => std::env::var("GHOSTLIGHT_RUNTIME_ID")
|
||||||
|
.context("GHOSTLIGHT_RUNTIME_ID is required outside managed runtime")?,
|
||||||
|
};
|
||||||
|
if runtime_id.is_empty() || runtime_id.trim() != runtime_id {
|
||||||
|
bail!("GHOSTLIGHT_RUNTIME_ID must be a canonical non-empty identity");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Production may bind but not serve its candidate socket, then publish
|
||||||
|
// Warming. Catalog, session and timeline state stay unopened until Idunn
|
||||||
|
// grants the lease bound to that exact observed process.
|
||||||
|
let mut write_lease_guard = None;
|
||||||
|
let mut idunn_health = match production_admission {
|
||||||
|
Some(ProductionAdmission { health, write_lease }) => {
|
||||||
|
write_lease.require_current()?;
|
||||||
|
write_lease_guard = Some(write_lease);
|
||||||
|
Some(health)
|
||||||
|
}
|
||||||
|
None => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
tokio::task::yield_now().await;
|
||||||
|
require_no_runtime_custody_failure(&mut fatal_events)?;
|
||||||
|
require_current_write_lease(write_lease_guard.as_ref())?;
|
||||||
|
if write_lease_guard.is_none() {
|
||||||
|
fs::create_dir_all(&runtime_root)?;
|
||||||
|
}
|
||||||
|
prepare_admitted_state_layout(&runtime_root)?;
|
||||||
|
require_current_write_lease(write_lease_guard.as_ref())?;
|
||||||
|
let mut catalog = Catalog::open(runtime_root.join("catalog.cc"))?;
|
||||||
|
// A seed runs only in the process that claimed it; any still Seeding was cut off.
|
||||||
|
let interrupted = catalog.fail_interrupted_seeds()?;
|
||||||
|
if interrupted > 0 {
|
||||||
|
tracing::warn!(interrupted, "seeds interrupted by the last shutdown were marked failed");
|
||||||
|
}
|
||||||
|
let shared = open_shared()?;
|
||||||
|
require_no_runtime_custody_failure(&mut fatal_events)?;
|
||||||
|
let wrapping_key = std::env::var_os("GHOSTLIGHT_SESSION_WRAPPING_KEY_FILE")
|
||||||
|
.map(PathBuf::from)
|
||||||
|
.unwrap_or_else(|| runtime_root.join("secrets/session-wrapping.key"));
|
||||||
|
let sessions = AppSessionOwner::open(service_root.join("app-sessions-v2.cc"), wrapping_key)?;
|
||||||
|
let odin_endpoint = dependency_bindings
|
||||||
|
.as_ref()
|
||||||
|
.map(|bindings| bindings.odin_rudp)
|
||||||
|
.map(Ok)
|
||||||
|
.unwrap_or_else(configured_odin_endpoint)?;
|
||||||
|
// Heimdall is discovered through Odin at use and is not an Idunn
|
||||||
|
// dependency; loopback-only, non-secret-bearing, app-bound envelopes are
|
||||||
|
// enforced regardless.
|
||||||
|
let heimdall = Arc::new(HeimdallClient::from_env(&runtime_id, odin_endpoint, None)?);
|
||||||
|
require_no_runtime_custody_failure(&mut fatal_events)?;
|
||||||
|
let mut state = AppState {
|
||||||
|
catalog: Arc::new(Mutex::new(catalog)),
|
||||||
|
timelines: Arc::new(Timelines::new(runtime_root.clone(), shared, fatal.clone())),
|
||||||
|
vaults: Arc::new(crate::vaults::SnapshotVaults::new(&runtime_root)),
|
||||||
|
scale: Arc::new(Scale::from_env()),
|
||||||
|
sessions: Arc::new(Mutex::new(sessions)),
|
||||||
|
heimdall,
|
||||||
|
auth: Arc::default(),
|
||||||
|
runtime_id,
|
||||||
|
runtime_health: None,
|
||||||
|
fatal,
|
||||||
|
};
|
||||||
|
require_no_runtime_custody_failure(&mut fatal_events)?;
|
||||||
|
require_current_write_lease(write_lease_guard.as_ref())?;
|
||||||
|
canonical_readiness(&state)
|
||||||
|
.await
|
||||||
|
.context("runtime is not ready for active signed health")?;
|
||||||
|
if let Some(publisher) = idunn_health.as_mut() {
|
||||||
|
let write_lease = write_lease_guard
|
||||||
|
.as_ref()
|
||||||
|
.context("production runtime lost its process write lease")?;
|
||||||
|
// Odin refuses Active until it has correlated the lease Idunn just
|
||||||
|
// granted; each call is a fresh sequenced message.
|
||||||
|
retry_until_deadline(
|
||||||
|
|| publisher.publish_active(write_lease),
|
||||||
|
INITIAL_PRESENCE_RETRY_CADENCE,
|
||||||
|
Instant::now() + WRITE_LEASE_WAIT_TIMEOUT,
|
||||||
|
"publishing initial active runtime presence",
|
||||||
|
Instant::now,
|
||||||
|
|duration| tokio::time::sleep(duration),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
require_current_write_lease(write_lease_guard.as_ref())?;
|
||||||
|
state.runtime_health = match (idunn_health, write_lease_guard) {
|
||||||
|
(Some(publisher), Some(write_lease)) => Some(RuntimeHealthOwner {
|
||||||
|
publisher: Arc::new(Mutex::new(publisher)),
|
||||||
|
write_lease: Arc::new(write_lease),
|
||||||
|
}),
|
||||||
|
(None, None) => None,
|
||||||
|
_ => bail!("managed runtime health authority is partial"),
|
||||||
|
};
|
||||||
|
let invite_socket = crate::invite::bind(&crate::invite::socket_path(&runtime_root))?;
|
||||||
|
let app = service_router(state.clone());
|
||||||
|
tracing::info!(address = %bound_address, "Ghostlight Dungeon serving");
|
||||||
|
let server = axum::serve(
|
||||||
|
listener,
|
||||||
|
app.into_make_service_with_connect_info::<SocketAddr>(),
|
||||||
|
);
|
||||||
|
tokio::select! {
|
||||||
|
result = server => result.context("Ghostlight HTTP server stopped"),
|
||||||
|
result = crate::invite::serve(invite_socket, state.catalog.clone()) => {
|
||||||
|
result?;
|
||||||
|
bail!("invite socket owner stopped while the daemon was serving")
|
||||||
|
}
|
||||||
|
result = maintain_runtime_health(state.clone()) => {
|
||||||
|
result?;
|
||||||
|
bail!("runtime readiness owner stopped while the daemon was serving")
|
||||||
|
}
|
||||||
|
result = run_refresh_loop(&state.sessions, state.heimdall.as_ref()) => {
|
||||||
|
result?;
|
||||||
|
bail!("app-session refresh owner stopped while the daemon was serving")
|
||||||
|
}
|
||||||
|
detail = fatal_events.recv() => {
|
||||||
|
bail!(
|
||||||
|
"runtime custody failed: {}",
|
||||||
|
detail.unwrap_or_else(|| "fatal signal channel closed".into())
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn cultnet_snapshot(
|
||||||
|
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||||
|
State(state): State<AppState>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
body: Bytes,
|
||||||
|
) -> Response {
|
||||||
|
// Idunn's route observation reaches this daemon straight over loopback and
|
||||||
|
// carries no proxy header. nginx sets `X-Real-IP` on every request it
|
||||||
|
// forwards, so a request that carries any of these came from the public
|
||||||
|
// side and finds no route here, whatever its peer address says.
|
||||||
|
if !peer.ip().is_loopback() || PROXY_HEADERS.iter().any(|name| headers.contains_key(*name)) {
|
||||||
|
return StatusCode::NOT_FOUND.into_response();
|
||||||
|
}
|
||||||
|
if headers.get(header::CONTENT_TYPE) != Some(&HeaderValue::from_static("application/msgpack")) {
|
||||||
|
return StatusCode::UNSUPPORTED_MEDIA_TYPE.into_response();
|
||||||
|
}
|
||||||
|
let message_id = match exact_route_observation_message_id(&body) {
|
||||||
|
Ok(message_id) => message_id,
|
||||||
|
Err(_) => return StatusCode::BAD_REQUEST.into_response(),
|
||||||
|
};
|
||||||
|
let Some(owner) = state.runtime_health.clone() else {
|
||||||
|
return StatusCode::SERVICE_UNAVAILABLE.into_response();
|
||||||
|
};
|
||||||
|
|
||||||
|
// Hold the one publisher across readiness observation and signing so a
|
||||||
|
// periodic publication cannot age the checked state before this challenge
|
||||||
|
// is bound into the signed record.
|
||||||
|
let write_lease = owner.write_lease.clone();
|
||||||
|
let mut publisher = owner.publisher.clone().lock_owned().await;
|
||||||
|
let ready = canonical_readiness(&state).await.is_ok();
|
||||||
|
let response = tokio::task::spawn_blocking(move || {
|
||||||
|
let response = publisher.route_observation(&message_id, ready, &write_lease)?;
|
||||||
|
encode_cultnet_message_to_vec(&response, CultNetWireContract::CultNetSchemaV0)
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
let Ok(Ok(response)) = response else {
|
||||||
|
return StatusCode::SERVICE_UNAVAILABLE.into_response();
|
||||||
|
};
|
||||||
|
(
|
||||||
|
StatusCode::OK,
|
||||||
|
[(header::CONTENT_TYPE, "application/msgpack")],
|
||||||
|
response,
|
||||||
|
)
|
||||||
|
.into_response()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn exact_route_observation_message_id(body: &[u8]) -> anyhow::Result<String> {
|
||||||
|
let request = decode_cultnet_message_from_slice(body, CultNetWireContract::CultNetSchemaV0)
|
||||||
|
.context("decoding route-observation request")?;
|
||||||
|
ensure!(
|
||||||
|
encode_cultnet_message_to_vec(&request, CultNetWireContract::CultNetSchemaV0)? == body,
|
||||||
|
"route-observation request is not canonical MessagePack"
|
||||||
|
);
|
||||||
|
let CultNetMessage::SnapshotRequest {
|
||||||
|
message_id,
|
||||||
|
schema_ids,
|
||||||
|
record_keys,
|
||||||
|
} = request
|
||||||
|
else {
|
||||||
|
bail!("route-observation request is not a snapshot request");
|
||||||
|
};
|
||||||
|
ensure!(
|
||||||
|
!message_id.is_empty(),
|
||||||
|
"route-observation message id is empty"
|
||||||
|
);
|
||||||
|
ensure!(
|
||||||
|
matches!(
|
||||||
|
schema_ids.as_deref(),
|
||||||
|
Some([schema_id]) if schema_id == GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA
|
||||||
|
) && matches!(
|
||||||
|
record_keys.as_deref(),
|
||||||
|
Some([record_key]) if record_key == GHOSTLIGHT_TARGET
|
||||||
|
),
|
||||||
|
"route-observation request is not the exact Ghostlight presence record"
|
||||||
|
);
|
||||||
|
let detail = format!("route-observation:{message_id}");
|
||||||
|
ensure!(
|
||||||
|
detail.len() <= 512 && !detail.chars().any(char::is_control),
|
||||||
|
"route-observation message id cannot be signed canonically"
|
||||||
|
);
|
||||||
|
Ok(message_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn health(State(state): State<AppState>) -> Response {
|
||||||
|
match runtime_readiness(&state).await {
|
||||||
|
Ok(health) => Json(health).into_response(),
|
||||||
|
Err(error) => (
|
||||||
|
StatusCode::SERVICE_UNAVAILABLE,
|
||||||
|
Json(json!({"status":"failed","message":error.to_string()})),
|
||||||
|
)
|
||||||
|
.into_response(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The custody every response rests on: the catalog and the session store.
|
||||||
|
async fn canonical_readiness(state: &AppState) -> anyhow::Result<Value> {
|
||||||
|
state
|
||||||
|
.catalog
|
||||||
|
.lock()
|
||||||
|
.await
|
||||||
|
.validate_custody()
|
||||||
|
.context("catalog is not ready")?;
|
||||||
|
state
|
||||||
|
.sessions
|
||||||
|
.lock()
|
||||||
|
.await
|
||||||
|
.validate_custody()
|
||||||
|
.context("app-session owner is not ready")?;
|
||||||
|
Ok(json!({
|
||||||
|
"schema":"ghostlight.service_health.v3",
|
||||||
|
"status":"ok",
|
||||||
|
"updatedAtUtc":Utc::now().to_rfc3339(),
|
||||||
|
"runtime":state.runtime_id,
|
||||||
|
"commit":option_env!("GHOSTLIGHT_BUILD_COMMIT").unwrap_or("development"),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn runtime_readiness(state: &AppState) -> anyhow::Result<Value> {
|
||||||
|
let mut health = canonical_readiness(state).await?;
|
||||||
|
let opened = state.timelines.opened().await;
|
||||||
|
let mut controller_status = "ok";
|
||||||
|
let mut play_status = "ok".to_owned();
|
||||||
|
for (id, host) in &opened {
|
||||||
|
match tokio::time::timeout(Duration::from_millis(100), host.controllers.custody_probe())
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(Ok(ControllerWorkCustody::Owned { .. })) => {}
|
||||||
|
Ok(Ok(ControllerWorkCustody::Uncertain { .. })) | Ok(Err(_)) => {
|
||||||
|
controller_status = "degraded";
|
||||||
|
}
|
||||||
|
Err(_) => controller_status = "busy",
|
||||||
|
}
|
||||||
|
// A retired unreadable play row is reported, not hidden.
|
||||||
|
if let Some(sidecar) = host.play.retired_row_sidecar() {
|
||||||
|
play_status = format!("a play-turn row of {id} was retired to {}", sidecar.display());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if state.timelines.shared().permits.available_permits() == 0 && controller_status == "ok" {
|
||||||
|
controller_status = "active";
|
||||||
|
}
|
||||||
|
health["openTimelines"] = json!(opened.len());
|
||||||
|
health["controllerStatus"] = Value::String(controller_status.into());
|
||||||
|
health["playStatus"] = Value::String(play_status);
|
||||||
|
Ok(health)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Idunn publishes Expected and starts the unit before it observes the
|
||||||
|
/// running process on a later tick and publishes the activation. Until then,
|
||||||
|
/// Odin refuses every Warming presence this daemon publishes. This is the
|
||||||
|
/// bound both the initial Warming publish retries against and
|
||||||
|
/// `wait_for_write_lease`'s own timeout.
|
||||||
|
const WRITE_LEASE_WAIT_TIMEOUT: Duration = Duration::from_secs(120);
|
||||||
|
|
||||||
|
/// Matches Muninn's own Warming re-publish cadence while tolerating the same
|
||||||
|
/// activation-publication gap.
|
||||||
|
const INITIAL_PRESENCE_RETRY_CADENCE: Duration = Duration::from_secs(2);
|
||||||
|
|
||||||
|
/// Retries `attempt` at `cadence` until it returns `Ok` or `deadline` passes,
|
||||||
|
/// returning the last error once the deadline is reached. `sleep` and `now`
|
||||||
|
/// are seams so the bounded-retry policy is provable without waiting.
|
||||||
|
async fn retry_until_deadline<T, Attempt, Sleep, SleepFut>(
|
||||||
|
mut attempt: Attempt,
|
||||||
|
cadence: Duration,
|
||||||
|
deadline: Instant,
|
||||||
|
what: &str,
|
||||||
|
mut now: impl FnMut() -> Instant,
|
||||||
|
mut sleep: Sleep,
|
||||||
|
) -> anyhow::Result<T>
|
||||||
|
where
|
||||||
|
Attempt: FnMut() -> anyhow::Result<T>,
|
||||||
|
Sleep: FnMut(Duration) -> SleepFut,
|
||||||
|
SleepFut: std::future::Future<Output = ()>,
|
||||||
|
{
|
||||||
|
loop {
|
||||||
|
match attempt() {
|
||||||
|
Ok(value) => return Ok(value),
|
||||||
|
Err(error) => {
|
||||||
|
tracing::warn!(%error, "{what} failed; retrying");
|
||||||
|
if now() >= deadline {
|
||||||
|
return Err(error).context(format!("{what} timed out"));
|
||||||
|
}
|
||||||
|
sleep(cadence).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn initialize_production_admission(
|
||||||
|
bound_endpoint: SocketAddr,
|
||||||
|
) -> anyhow::Result<Option<ProductionAdmission>> {
|
||||||
|
let Some(mut publisher) = RuntimePresencePublisher::from_environment(bound_endpoint)? else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
// Each `publish_warming()` mints a fresh sequence and timestamp, so a
|
||||||
|
// retried publish is a new message Odin evaluates, never a duplicate.
|
||||||
|
let warming = retry_until_deadline(
|
||||||
|
|| publisher.publish_warming(),
|
||||||
|
INITIAL_PRESENCE_RETRY_CADENCE,
|
||||||
|
Instant::now() + WRITE_LEASE_WAIT_TIMEOUT,
|
||||||
|
"publishing initial Warming runtime presence",
|
||||||
|
Instant::now,
|
||||||
|
|duration| tokio::time::sleep(duration),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
let write_lease = publisher
|
||||||
|
.wait_for_write_lease(&warming, WRITE_LEASE_WAIT_TIMEOUT)
|
||||||
|
.await
|
||||||
|
.with_context(|| {
|
||||||
|
format!(
|
||||||
|
"waiting for process lease bound to Warming {}",
|
||||||
|
warming.canonical_sha256()
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
Ok(Some(ProductionAdmission {
|
||||||
|
health: publisher,
|
||||||
|
write_lease,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn maintain_runtime_health(state: AppState) -> anyhow::Result<()> {
|
||||||
|
let mut interval = tokio::time::interval(Duration::from_secs(10));
|
||||||
|
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||||
|
loop {
|
||||||
|
interval.tick().await;
|
||||||
|
canonical_readiness(&state)
|
||||||
|
.await
|
||||||
|
.context("runtime is not ready for signed health")?;
|
||||||
|
let Some(owner) = state.runtime_health.clone() else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
owner
|
||||||
|
.write_lease
|
||||||
|
.require_current()
|
||||||
|
.context("runtime process write lease is not current")?;
|
||||||
|
let mut publisher = owner.publisher.clone().lock_owned().await;
|
||||||
|
let published = tokio::task::spawn_blocking(move || {
|
||||||
|
publisher.republish_active()?;
|
||||||
|
Ok::<(), anyhow::Error>(())
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
let Ok(result) = published else {
|
||||||
|
tracing::warn!("runtime-presence worker panicked; publication will retry");
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if let Err(error) = result {
|
||||||
|
tracing::warn!(%error, "signed runtime-presence publication failed");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn candidate_bind() -> anyhow::Result<SocketAddr> {
|
||||||
|
match std::env::var(IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT) {
|
||||||
|
Ok(value) => value
|
||||||
|
.parse()
|
||||||
|
.context("Idunn candidate bind is not a socket address"),
|
||||||
|
Err(_) => {
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
bail!("{IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT} is mandatory on Linux");
|
||||||
|
#[cfg(not(target_os = "linux"))]
|
||||||
|
return Ok("127.0.0.1:8831".parse()?);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn configured_odin_endpoint() -> anyhow::Result<SocketAddr> {
|
||||||
|
std::env::var("GHOSTLIGHT_ODIN_RUDP")
|
||||||
|
.context("GHOSTLIGHT_ODIN_RUDP is required")?
|
||||||
|
.parse()
|
||||||
|
.context("GHOSTLIGHT_ODIN_RUDP is not a socket address")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn require_current_write_lease(lease: Option<&ProcessWriteLeaseGuard>) -> anyhow::Result<()> {
|
||||||
|
match lease {
|
||||||
|
Some(lease) => lease.require_current(),
|
||||||
|
None => Ok(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn require_no_runtime_custody_failure(
|
||||||
|
failures: &mut mpsc::UnboundedReceiver<String>,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
match failures.try_recv() {
|
||||||
|
Ok(detail) => bail!("runtime custody failed before serving: {detail}"),
|
||||||
|
Err(mpsc::error::TryRecvError::Empty) => Ok(()),
|
||||||
|
Err(mpsc::error::TryRecvError::Disconnected) => {
|
||||||
|
bail!("runtime custody signal channel closed before serving")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
/// Counts every call and the usage the connector reports, around the real
|
||||||
|
/// port, for the live check.
|
||||||
|
struct CountingPort {
|
||||||
|
inner: Arc<dyn InferencePort>,
|
||||||
|
calls: std::sync::atomic::AtomicU64,
|
||||||
|
usage: std::sync::Mutex<(u64, u64)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl InferencePort for CountingPort {
|
||||||
|
fn prepare(
|
||||||
|
&self,
|
||||||
|
request: ghostlight::InferenceRequest,
|
||||||
|
) -> Result<ghostlight::PreparedInference, ghostlight::InferenceFault> {
|
||||||
|
self.inner.prepare(request)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn infer(
|
||||||
|
&self,
|
||||||
|
request: ghostlight::PreparedInference,
|
||||||
|
) -> Result<ghostlight::InferenceOutput, ghostlight::InferenceFault> {
|
||||||
|
self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||||
|
let output = self.inner.infer(request).await?;
|
||||||
|
let seen = serde_json::to_value(&output).unwrap_or_default();
|
||||||
|
let mut usage = self.usage.lock().unwrap();
|
||||||
|
usage.0 += seen["usage"]["prompt"].as_u64().unwrap_or(0);
|
||||||
|
usage.1 += seen["usage"]["completion"].as_u64().unwrap_or(0);
|
||||||
|
Ok(output)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Live: Begin on an imported snapshot through the real connector.
|
||||||
|
/// `GHOSTLIGHT_LIVE_STATE_ROOT` holds `snapshots/` from `import-vault`,
|
||||||
|
/// `GHOSTLIGHT_LIVE_PROFILE` names the profile, and the connector address
|
||||||
|
/// and key credential are the daemon's own (`GHOSTLIGHT_CONNECTOR_ADDR`,
|
||||||
|
/// `$CREDENTIALS_DIRECTORY/connector-key`). Spends real credit.
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||||
|
#[ignore = "live: spends connector credit; run on Yggdrasil under a unit that loads the connector key"]
|
||||||
|
async fn live_seeded_begin_reaches_ready_with_a_place_and_people() {
|
||||||
|
use crate::{
|
||||||
|
begin::{BeginRequest, Scale, begin, tests::principal}, catalog::SeedStatus,
|
||||||
|
catalog::Catalog,
|
||||||
|
state_layout::prepare_admitted_state_layout,
|
||||||
|
timelines::{Shared, Timelines},
|
||||||
|
};
|
||||||
|
let root = PathBuf::from(std::env::var("GHOSTLIGHT_LIVE_STATE_ROOT").unwrap());
|
||||||
|
let profile = std::env::var("GHOSTLIGHT_LIVE_PROFILE").unwrap();
|
||||||
|
prepare_admitted_state_layout(&root).unwrap();
|
||||||
|
let shared = open_shared().unwrap();
|
||||||
|
let counting = Arc::new(CountingPort {
|
||||||
|
inner: shared.inference.clone(),
|
||||||
|
calls: Default::default(),
|
||||||
|
usage: Default::default(),
|
||||||
|
});
|
||||||
|
let shared = Shared { inference: counting.clone(), ..shared };
|
||||||
|
let (fatal, _fatal_events) = mpsc::unbounded_channel();
|
||||||
|
let timelines = Timelines::new(root.clone(), shared, fatal);
|
||||||
|
let catalog = Arc::new(Mutex::new(Catalog::open(root.join("catalog.cc")).unwrap()));
|
||||||
|
let vaults = crate::vaults::SnapshotVaults::new(&root);
|
||||||
|
let scale = Arc::new(Scale::from_env());
|
||||||
|
|
||||||
|
let started = Instant::now();
|
||||||
|
let begun = begin(
|
||||||
|
&catalog,
|
||||||
|
&timelines,
|
||||||
|
&vaults,
|
||||||
|
&scale,
|
||||||
|
&principal("live"),
|
||||||
|
BeginRequest {
|
||||||
|
key: uuid::Uuid::new_v4().to_string(),
|
||||||
|
title: "Ghostlight Live".into(),
|
||||||
|
name: "Deru".into(),
|
||||||
|
brief: None,
|
||||||
|
vault: Some(profile.clone()),
|
||||||
|
era: None,
|
||||||
|
lenses: None,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
println!("LIVE begin returned after {:?}: {}", started.elapsed(), begun.reached);
|
||||||
|
let ready = loop {
|
||||||
|
let status = catalog.lock().await.seed_status(&begun.timeline).cloned();
|
||||||
|
match status {
|
||||||
|
None => break started.elapsed(),
|
||||||
|
Some(SeedStatus::Failed(reason)) => panic!("the seed failed: {reason}"),
|
||||||
|
Some(SeedStatus::Seeding) if started.elapsed() > Duration::from_secs(1800) => {
|
||||||
|
panic!("still seeding after 30 minutes")
|
||||||
|
}
|
||||||
|
Some(SeedStatus::Seeding) => tokio::time::sleep(Duration::from_secs(2)).await,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let (calls, usage) = (counting.calls.load(std::sync::atomic::Ordering::SeqCst), *counting.usage.lock().unwrap());
|
||||||
|
println!("LIVE ready after {ready:?}; calls={calls} prompt_tokens={} completion_tokens={}", usage.0, usage.1);
|
||||||
|
let host = timelines.host(&begun.timeline).await.unwrap();
|
||||||
|
// A position is not public on the snapshot; the Debug text names it by
|
||||||
|
// the same entity id a place carries.
|
||||||
|
let standing = |world: &ghostlight::WorldSnapshot, place: &ghostlight::PlaceSnapshot| -> Vec<String> {
|
||||||
|
let at = format!("position: Some({:?})", place.id);
|
||||||
|
world.subjects.iter().filter(|subject| format!("{subject:?}").contains(&at)).map(|subject| subject.label.clone()).collect()
|
||||||
|
};
|
||||||
|
let report = |label: &str, world: &ghostlight::WorldSnapshot| {
|
||||||
|
println!("LIVE {label}: phase={:?}", world.phase);
|
||||||
|
for place in &world.places {
|
||||||
|
println!("LIVE place {} <- {:?}", place.label, standing(world, place));
|
||||||
|
}
|
||||||
|
for subject in &world.subjects {
|
||||||
|
println!("LIVE subject {:?} {} qualified={}", subject.kind, subject.label, subject.qualified);
|
||||||
|
}
|
||||||
|
for row in &world.scale_deficit {
|
||||||
|
println!("LIVE row {:?} target={} qualified={} deficit={}", row.kind, row.target, row.qualified, row.deficit);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let world = host.world.snapshot().await.unwrap();
|
||||||
|
report("after seed", &world);
|
||||||
|
assert_eq!(world.phase, ghostlight::WorldPhase::Active);
|
||||||
|
let authored = world.places.iter().filter(|place| place.label != "The Commons" && place.label != "Ghostlight Live").count();
|
||||||
|
assert!(authored >= 2, "the seed authored places beyond the root and The Commons, got {authored}");
|
||||||
|
let person = world.scale_deficit.iter().find(|row| row.kind == ghostlight::SubjectKind::Person).unwrap();
|
||||||
|
assert!(person.qualified >= 2, "at least two qualifying people");
|
||||||
|
|
||||||
|
// The first run-ahead sweep, then the world as play would meet it.
|
||||||
|
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||||
|
let sweep_started = Instant::now();
|
||||||
|
while host.sweeping.try_lock().is_err() && sweep_started.elapsed() < Duration::from_secs(1800) {
|
||||||
|
tokio::time::sleep(Duration::from_secs(2)).await;
|
||||||
|
}
|
||||||
|
let (calls, usage) = (counting.calls.load(std::sync::atomic::Ordering::SeqCst), *counting.usage.lock().unwrap());
|
||||||
|
println!(
|
||||||
|
"LIVE after run-ahead at {:?}: calls={calls} prompt_tokens={} completion_tokens={}",
|
||||||
|
started.elapsed(),
|
||||||
|
usage.0,
|
||||||
|
usage.1
|
||||||
|
);
|
||||||
|
report("after run-ahead", &host.world.snapshot().await.unwrap());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn lanes_default_to_the_ruled_tiers_and_each_reads_its_own_override() {
|
||||||
|
let (models, play) = lane_models_from(|_| None);
|
||||||
|
assert_eq!(models.projector, "claude-opus-5-5", "the narrator");
|
||||||
|
assert_eq!(models.persona, "claude-opus-5-5");
|
||||||
|
assert_eq!(models.elaborator, "claude-sonnet-5-5");
|
||||||
|
assert_eq!(play, "claude-sonnet-5-5");
|
||||||
|
assert_eq!(models.interpreter, "claude-haiku-5-5");
|
||||||
|
assert_eq!(models.operational_agent, "claude-haiku-5-5");
|
||||||
|
for (name, lane) in [
|
||||||
|
("GHOSTLIGHT_CONTROLLER_PROJECTOR_MODEL", 0),
|
||||||
|
("GHOSTLIGHT_CONTROLLER_PERSONA_MODEL", 1),
|
||||||
|
("GHOSTLIGHT_CONTROLLER_INTERPRETER_MODEL", 2),
|
||||||
|
("GHOSTLIGHT_CONTROLLER_OPERATIONAL_MODEL", 3),
|
||||||
|
("GHOSTLIGHT_CONTROLLER_ELABORATOR_MODEL", 4),
|
||||||
|
("GHOSTLIGHT_PLAY_MODEL", 5),
|
||||||
|
] {
|
||||||
|
let (models, play) = lane_models_from(|asked| (asked == name).then(|| "override".to_owned()));
|
||||||
|
let mut all = models.each().to_vec();
|
||||||
|
all.push(&play);
|
||||||
|
let overridden: Vec<usize> = all
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.filter(|(_, model)| **model == "override")
|
||||||
|
.map(|(index, _)| index)
|
||||||
|
.collect();
|
||||||
|
assert_eq!(overridden, vec![lane], "{name} moves exactly its own lane");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct FakeClock {
|
||||||
|
now: std::cell::Cell<Instant>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FakeClock {
|
||||||
|
fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
now: std::cell::Cell::new(Instant::now()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn now(&self) -> Instant {
|
||||||
|
self.now.get()
|
||||||
|
}
|
||||||
|
fn advance(&self, by: Duration) {
|
||||||
|
self.now.set(self.now.get() + by);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn retry_until_deadline_returns_the_first_accepted_value() {
|
||||||
|
let clock = FakeClock::new();
|
||||||
|
let deadline = clock.now() + Duration::from_secs(120);
|
||||||
|
let mut calls = 0;
|
||||||
|
let result = retry_until_deadline(
|
||||||
|
|| {
|
||||||
|
calls += 1;
|
||||||
|
if calls < 3 {
|
||||||
|
Err(anyhow::anyhow!("refused (attempt {calls})"))
|
||||||
|
} else {
|
||||||
|
Ok(format!("accepted on attempt {calls}"))
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Duration::from_secs(2),
|
||||||
|
deadline,
|
||||||
|
"test publish",
|
||||||
|
|| clock.now(),
|
||||||
|
|cadence| {
|
||||||
|
clock.advance(cadence);
|
||||||
|
std::future::ready(())
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(result.unwrap(), "accepted on attempt 3");
|
||||||
|
assert_eq!(calls, 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn retry_until_deadline_fails_with_the_last_error_after_the_window() {
|
||||||
|
let clock = FakeClock::new();
|
||||||
|
let deadline = clock.now() + Duration::from_secs(10);
|
||||||
|
let mut calls = 0;
|
||||||
|
let result: anyhow::Result<()> = retry_until_deadline(
|
||||||
|
|| {
|
||||||
|
calls += 1;
|
||||||
|
Err(anyhow::anyhow!("refused (attempt {calls})"))
|
||||||
|
},
|
||||||
|
Duration::from_secs(2),
|
||||||
|
deadline,
|
||||||
|
"test publish",
|
||||||
|
|| clock.now(),
|
||||||
|
|cadence| {
|
||||||
|
clock.advance(cadence);
|
||||||
|
std::future::ready(())
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let error = result.unwrap_err();
|
||||||
|
assert!(format!("{error:#}").contains("test publish timed out"));
|
||||||
|
assert!(format!("{error:#}").contains("refused (attempt"));
|
||||||
|
assert_eq!(calls, 6);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The connector key is a credential path, never a value: the binding
|
||||||
|
/// carries the path Idunn's credential delivered and the caller id, and
|
||||||
|
/// nothing else of it.
|
||||||
|
#[test]
|
||||||
|
fn the_connector_key_is_bound_by_credential_path_only() {
|
||||||
|
// SAFETY: the test sets and clears process env it alone reads.
|
||||||
|
unsafe {
|
||||||
|
std::env::set_var(CONNECTOR_ADDRESS_ENVIRONMENT, "127.0.0.1:7001");
|
||||||
|
std::env::set_var(
|
||||||
|
CONNECTOR_KEY_FILE_ENVIRONMENT,
|
||||||
|
"/run/credentials/idunn-ghostlight-x.service/GHOSTLIGHT_CONNECTOR_KEY_FILE",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let binding = connector_binding().unwrap();
|
||||||
|
assert_eq!(binding.caller_runtime_id, "ghostlight");
|
||||||
|
assert_eq!(
|
||||||
|
binding.key_path,
|
||||||
|
PathBuf::from("/run/credentials/idunn-ghostlight-x.service/GHOSTLIGHT_CONNECTOR_KEY_FILE")
|
||||||
|
);
|
||||||
|
unsafe {
|
||||||
|
std::env::set_var(CONNECTOR_KEY_FILE_ENVIRONMENT, "relative/key");
|
||||||
|
}
|
||||||
|
assert!(connector_binding().is_err(), "a relative path is no credential");
|
||||||
|
unsafe {
|
||||||
|
std::env::remove_var(CONNECTOR_KEY_FILE_ENVIRONMENT);
|
||||||
|
}
|
||||||
|
assert!(connector_binding().is_err(), "no credential path, no binding");
|
||||||
|
unsafe {
|
||||||
|
std::env::remove_var(CONNECTOR_ADDRESS_ENVIRONMENT);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
619
crates/ghostlight-dungeon/src/session_refresh.rs
Normal file
|
|
@ -0,0 +1,619 @@
|
||||||
|
//! The app-session refresh loop: renews Heimdall sessions before they lapse
|
||||||
|
//! and revokes any whose custody changed.
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
app_session::{AppSessionOwner, RefreshRefusal},
|
||||||
|
heimdall::{self, HeimdallDenied, SessionRefresher, VerificationUnavailable},
|
||||||
|
};
|
||||||
|
use anyhow::Context;
|
||||||
|
use chrono::Utc;
|
||||||
|
use std::{collections::HashMap, time::Duration};
|
||||||
|
use tokio::sync::Mutex;
|
||||||
|
|
||||||
|
const SESSION_REFRESH_PERIOD: Duration = Duration::from_secs(60);
|
||||||
|
|
||||||
|
/// Runs `refresh_due_sessions` once per `SESSION_REFRESH_PERIOD` for as long
|
||||||
|
/// as the daemon serves. The receipts it holds are Heimdall refreshes already
|
||||||
|
/// spent upstream whose verification could not yet be judged.
|
||||||
|
pub(crate) async fn run_refresh_loop(
|
||||||
|
sessions: &Mutex<AppSessionOwner>,
|
||||||
|
heimdall: &(impl SessionRefresher + ?Sized),
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
let mut interval = tokio::time::interval(SESSION_REFRESH_PERIOD);
|
||||||
|
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||||
|
let mut unverified = HashMap::new();
|
||||||
|
loop {
|
||||||
|
interval.tick().await;
|
||||||
|
refresh_due_sessions(sessions, heimdall, &mut unverified).await?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One pass of the refresh loop over every session due for refresh.
|
||||||
|
/// `unverified` holds, per session, a receipt Heimdall issued for a refresh
|
||||||
|
/// that is already spent upstream but whose signing keys could not be
|
||||||
|
/// fetched: the next pass verifies it instead of refreshing again.
|
||||||
|
async fn refresh_due_sessions(
|
||||||
|
sessions: &Mutex<AppSessionOwner>,
|
||||||
|
heimdall: &(impl SessionRefresher + ?Sized),
|
||||||
|
unverified: &mut HashMap<String, heimdall::AuthCompletionReceipt>,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
let candidates = sessions
|
||||||
|
.lock()
|
||||||
|
.await
|
||||||
|
.sessions_due_for_refresh(Utc::now(), chrono::Duration::minutes(2))
|
||||||
|
.context("app-session refresh scan lost custody")?;
|
||||||
|
unverified.retain(|cookie_hash, _| {
|
||||||
|
candidates
|
||||||
|
.iter()
|
||||||
|
.any(|candidate| &candidate.cookie_hash == cookie_hash)
|
||||||
|
});
|
||||||
|
for candidate in candidates {
|
||||||
|
let completion = match unverified.remove(&candidate.cookie_hash) {
|
||||||
|
Some(completion) => completion,
|
||||||
|
None => {
|
||||||
|
let idempotency =
|
||||||
|
crate::app_session::refresh_idempotency_key(&candidate.refresh_claim);
|
||||||
|
match heimdall.refresh(&candidate.refresh_claim, &idempotency).await {
|
||||||
|
Ok(value) => value,
|
||||||
|
Err(error) if error.downcast_ref::<HeimdallDenied>().is_some() => {
|
||||||
|
// Heimdall refused this refresh claim: it can never succeed.
|
||||||
|
tracing::warn!(%error, "Heimdall denied the refresh; revoking the local session");
|
||||||
|
let mut sessions = sessions.lock().await;
|
||||||
|
if let Err(revoke_error) =
|
||||||
|
sessions.revoke_cookie_hash(&candidate.cookie_hash)
|
||||||
|
{
|
||||||
|
return Err(revoke_error)
|
||||||
|
.context("denied Heimdall refresh could not revoke local custody");
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Err(error) => {
|
||||||
|
tracing::warn!(%error, "Heimdall refresh transport unavailable");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let verified = match heimdall.verify_refresh(completion.clone()).await {
|
||||||
|
Ok(value) => value,
|
||||||
|
Err(error) if error.downcast_ref::<VerificationUnavailable>().is_some() => {
|
||||||
|
// The claim is spent upstream and the receipt may be genuine:
|
||||||
|
// keep it and verify again on the next pass.
|
||||||
|
tracing::warn!(%error, "Heimdall refresh receipt could not be verified yet");
|
||||||
|
unverified.insert(candidate.cookie_hash.clone(), completion);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Err(error) => {
|
||||||
|
tracing::warn!(%error, "Heimdall refresh receipt was invalid");
|
||||||
|
let mut sessions = sessions.lock().await;
|
||||||
|
if let Err(revoke_error) = sessions.revoke_cookie_hash(&candidate.cookie_hash) {
|
||||||
|
return Err(revoke_error)
|
||||||
|
.context("invalid Heimdall refresh could not revoke local custody");
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if verified.heimdall_session_id() != candidate.heimdall_session_id
|
||||||
|
|| crate::app_session::secret_hash(&format!(
|
||||||
|
"heimdall-account:{}",
|
||||||
|
verified.account_id()
|
||||||
|
)) != candidate.account_subject_hash
|
||||||
|
{
|
||||||
|
tracing::warn!("Heimdall refresh changed local session custody");
|
||||||
|
let mut sessions = sessions.lock().await;
|
||||||
|
if let Err(revoke_error) = sessions.revoke_cookie_hash(&candidate.cookie_hash) {
|
||||||
|
return Err(revoke_error)
|
||||||
|
.context("changed Heimdall custody could not revoke local session");
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let mut sessions = sessions.lock().await;
|
||||||
|
if let Err(error) =
|
||||||
|
sessions.apply_refresh(&candidate.cookie_hash, candidate.access_revision, verified)
|
||||||
|
{
|
||||||
|
if !sessions.is_healthy() {
|
||||||
|
return Err(error).context("app-session refresh commit lost custody");
|
||||||
|
}
|
||||||
|
tracing::warn!(%error, "local app session refused Heimdall refresh");
|
||||||
|
// The refresh claim is spent upstream, so a receipt that went
|
||||||
|
// backwards leaves nothing to retry. A session that merely moved
|
||||||
|
// is newer state: the next scan decides.
|
||||||
|
if error.downcast_ref::<RefreshRefusal>()
|
||||||
|
== Some(&RefreshRefusal::RevisionWentBackwards)
|
||||||
|
&& let Err(revoke_error) = sessions.revoke_cookie_hash(&candidate.cookie_hash)
|
||||||
|
{
|
||||||
|
return Err(revoke_error)
|
||||||
|
.context("backwards Heimdall refresh could not revoke local session");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Idunn publishes Expected and starts the unit before it observes the
|
||||||
|
/// running process on a later tick and publishes the activation
|
||||||
|
/// (Idunn/src/control_plane.rs). Until that activation exists, Odin refuses
|
||||||
|
|
||||||
|
/// queue and records the claim and idempotency key it was sent.
|
||||||
|
#[cfg(test)]
|
||||||
|
mod refresh_loop_tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::heimdall::{AuthCompletionReceipt, HeimdallClient, VerifiedSessionRefresh};
|
||||||
|
use anyhow::bail;
|
||||||
|
use std::{collections::VecDeque, sync::Mutex as StdMutex};
|
||||||
|
|
||||||
|
enum Reply {
|
||||||
|
Deny,
|
||||||
|
Timeout,
|
||||||
|
Receipt { revision: u64, claim: &'static str },
|
||||||
|
/// A receipt for the same claim but another Heimdall session.
|
||||||
|
OtherSession,
|
||||||
|
/// A receipt for the same claim but another account.
|
||||||
|
OtherAccount,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What `verify_refresh` answers; an empty queue accepts the receipt.
|
||||||
|
enum Verdict {
|
||||||
|
/// The signing keys could not be fetched.
|
||||||
|
Unavailable,
|
||||||
|
/// The receipt positively fails verification.
|
||||||
|
Invalid,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct ScriptedHeimdall {
|
||||||
|
replies: StdMutex<VecDeque<Reply>>,
|
||||||
|
verdicts: StdMutex<VecDeque<Verdict>>,
|
||||||
|
verifications: StdMutex<usize>,
|
||||||
|
/// While answering a refresh, apply a newer revision to this store,
|
||||||
|
/// as a concurrent refresh of the same session would.
|
||||||
|
moving: Option<std::sync::Arc<Mutex<AppSessionOwner>>>,
|
||||||
|
pending: StdMutex<Option<VerifiedSessionRefresh>>,
|
||||||
|
calls: StdMutex<Vec<(String, String)>>,
|
||||||
|
/// Verify receipts with this real client, against the access token
|
||||||
|
/// each receipt carries, instead of from the verdict queue.
|
||||||
|
real: Option<(HeimdallClient, String)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ScriptedHeimdall {
|
||||||
|
fn answering(replies: Vec<Reply>) -> Self {
|
||||||
|
Self {
|
||||||
|
replies: StdMutex::new(replies.into()),
|
||||||
|
..Self::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn verifying(mut self, verdicts: Vec<Verdict>) -> Self {
|
||||||
|
self.verdicts = StdMutex::new(verdicts.into());
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
fn verifying_for_real(mut self, client: HeimdallClient, token: String) -> Self {
|
||||||
|
self.real = Some((client, token));
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
fn verifications(&self) -> usize {
|
||||||
|
*self.verifications.lock().unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn calls(&self) -> Vec<(String, String)> {
|
||||||
|
self.calls.lock().unwrap().clone()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl SessionRefresher for ScriptedHeimdall {
|
||||||
|
async fn refresh(
|
||||||
|
&self,
|
||||||
|
refresh_token: &str,
|
||||||
|
idempotency_key: &str,
|
||||||
|
) -> anyhow::Result<AuthCompletionReceipt> {
|
||||||
|
self.calls
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.push((refresh_token.into(), idempotency_key.into()));
|
||||||
|
if let Some(sessions) = &self.moving {
|
||||||
|
let mut sessions = sessions.lock().await;
|
||||||
|
let candidate = sessions
|
||||||
|
.sessions_due_for_refresh(Utc::now(), chrono::Duration::minutes(2))
|
||||||
|
.unwrap()
|
||||||
|
.remove(0);
|
||||||
|
sessions
|
||||||
|
.apply_refresh(
|
||||||
|
&candidate.cookie_hash,
|
||||||
|
candidate.access_revision,
|
||||||
|
VerifiedSessionRefresh::fixture(
|
||||||
|
"operator-account",
|
||||||
|
"heimdall-session",
|
||||||
|
candidate.access_revision + 1,
|
||||||
|
Utc::now() + chrono::Duration::seconds(90),
|
||||||
|
Utc::now() + chrono::Duration::days(1),
|
||||||
|
"claim-moved",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
match self.replies.lock().unwrap().pop_front().expect("scripted reply") {
|
||||||
|
Reply::Deny => Err(HeimdallDenied {
|
||||||
|
diagnostics: "Idempotency key was reused".into(),
|
||||||
|
}
|
||||||
|
.into()),
|
||||||
|
Reply::Timeout => bail!("Heimdall private command timed out"),
|
||||||
|
reply @ (Reply::Receipt { .. } | Reply::OtherSession | Reply::OtherAccount) => {
|
||||||
|
let (account, session, revision, claim) = match reply {
|
||||||
|
Reply::OtherSession => ("operator-account", "other-session", 1, "claim-1"),
|
||||||
|
Reply::OtherAccount => ("other-account", "heimdall-session", 1, "claim-1"),
|
||||||
|
Reply::Receipt { revision, claim } => {
|
||||||
|
("operator-account", "heimdall-session", revision, claim)
|
||||||
|
}
|
||||||
|
_ => unreachable!("matched above"),
|
||||||
|
};
|
||||||
|
*self.pending.lock().unwrap() = Some(VerifiedSessionRefresh::fixture(
|
||||||
|
account,
|
||||||
|
session,
|
||||||
|
revision,
|
||||||
|
Utc::now() + chrono::Duration::seconds(90),
|
||||||
|
Utc::now() + chrono::Duration::days(1),
|
||||||
|
claim,
|
||||||
|
));
|
||||||
|
Ok(AuthCompletionReceipt {
|
||||||
|
status: "authenticated".into(),
|
||||||
|
handle: None,
|
||||||
|
error: None,
|
||||||
|
account: None,
|
||||||
|
session: None,
|
||||||
|
access_token: self.real.as_ref().map(|(_, token)| token.clone()),
|
||||||
|
refresh_token: None,
|
||||||
|
refresh: None,
|
||||||
|
shared_capabilities: Vec::new(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn verify_refresh(
|
||||||
|
&self,
|
||||||
|
completion: AuthCompletionReceipt,
|
||||||
|
) -> anyhow::Result<VerifiedSessionRefresh> {
|
||||||
|
*self.verifications.lock().unwrap() += 1;
|
||||||
|
if let Some((client, _)) = &self.real {
|
||||||
|
return client.verify_refresh(completion).await;
|
||||||
|
}
|
||||||
|
match self.verdicts.lock().unwrap().pop_front() {
|
||||||
|
Some(Verdict::Unavailable) => {
|
||||||
|
Err(VerificationUnavailable::new("timed out").into())
|
||||||
|
}
|
||||||
|
Some(Verdict::Invalid) => bail!("Heimdall access token signature is invalid"),
|
||||||
|
None => Ok(self.pending.lock().unwrap().take().expect("scripted receipt")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A store holding one live session at `revision` whose access expires in
|
||||||
|
/// a minute, so every pass finds it due.
|
||||||
|
fn due_session(
|
||||||
|
revision: u64,
|
||||||
|
) -> (tempfile::TempDir, std::sync::Arc<Mutex<AppSessionOwner>>, String) {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let key = directory.path().join("session.key");
|
||||||
|
std::fs::write(&key, [23_u8; 32]).unwrap();
|
||||||
|
let mut owner = AppSessionOwner::open(directory.path().join("sessions.cc"), &key).unwrap();
|
||||||
|
let cookie = owner
|
||||||
|
.create_session(heimdall::VerifiedSessionAdmission::fixture(
|
||||||
|
"operator-account",
|
||||||
|
"heimdall-session",
|
||||||
|
revision,
|
||||||
|
Utc::now() + chrono::Duration::seconds(60),
|
||||||
|
Utc::now() + chrono::Duration::days(1),
|
||||||
|
"claim-0",
|
||||||
|
))
|
||||||
|
.unwrap();
|
||||||
|
(directory, std::sync::Arc::new(Mutex::new(owner)), cookie)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One refresh pass with no receipt carried over from an earlier one.
|
||||||
|
async fn pass(sessions: &Mutex<AppSessionOwner>, heimdall: &ScriptedHeimdall) {
|
||||||
|
refresh_due_sessions(sessions, heimdall, &mut HashMap::new())
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn is_live(sessions: &Mutex<AppSessionOwner>, cookie: &str) -> bool {
|
||||||
|
sessions
|
||||||
|
.lock()
|
||||||
|
.await
|
||||||
|
.account_for_cookie(cookie, Utc::now())
|
||||||
|
.unwrap()
|
||||||
|
.is_some()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Default)]
|
||||||
|
struct Captured(std::sync::Arc<StdMutex<Vec<u8>>>);
|
||||||
|
|
||||||
|
impl std::io::Write for Captured {
|
||||||
|
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
|
||||||
|
self.0.lock().unwrap().extend_from_slice(bytes);
|
||||||
|
Ok(bytes.len())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn flush(&mut self) -> std::io::Result<()> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for Captured {
|
||||||
|
type Writer = Captured;
|
||||||
|
|
||||||
|
fn make_writer(&'a self) -> Captured {
|
||||||
|
self.clone()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_real_refresh_at_an_equal_revision_is_applied_and_the_session_stays_live() {
|
||||||
|
let (_directory, sessions, cookie) = due_session(1);
|
||||||
|
let heimdall = ScriptedHeimdall::answering(vec![
|
||||||
|
Reply::Receipt { revision: 1, claim: "claim-1" },
|
||||||
|
Reply::Timeout,
|
||||||
|
]);
|
||||||
|
pass(&sessions, &heimdall).await;
|
||||||
|
assert!(is_live(&sessions, &cookie).await);
|
||||||
|
// The wrapped claim is the receipt's: the next refresh spends it.
|
||||||
|
pass(&sessions, &heimdall).await;
|
||||||
|
assert_eq!(heimdall.calls()[1].0, "claim-1");
|
||||||
|
assert!(is_live(&sessions, &cookie).await);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_retry_of_the_same_refresh_sends_the_same_key() {
|
||||||
|
let (_directory, sessions, cookie) = due_session(1);
|
||||||
|
let heimdall = ScriptedHeimdall::answering(vec![Reply::Timeout, Reply::Timeout]);
|
||||||
|
pass(&sessions, &heimdall).await;
|
||||||
|
pass(&sessions, &heimdall).await;
|
||||||
|
let calls = heimdall.calls();
|
||||||
|
assert_eq!(calls.len(), 2, "a transport failure leaves the session offered");
|
||||||
|
assert_eq!(calls[0], calls[1]);
|
||||||
|
assert!(is_live(&sessions, &cookie).await);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn the_refresh_after_a_successful_one_sends_a_new_key() {
|
||||||
|
let (_directory, sessions, _cookie) = due_session(1);
|
||||||
|
let heimdall = ScriptedHeimdall::answering(vec![
|
||||||
|
Reply::Receipt { revision: 1, claim: "claim-1" },
|
||||||
|
Reply::Timeout,
|
||||||
|
]);
|
||||||
|
pass(&sessions, &heimdall).await;
|
||||||
|
pass(&sessions, &heimdall).await;
|
||||||
|
let calls = heimdall.calls();
|
||||||
|
assert_ne!(calls[0].1, calls[1].1);
|
||||||
|
assert!(calls.iter().all(|(claim, key)| !key.contains(claim)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_receipt_with_a_lower_revision_is_refused_and_the_session_revoked() {
|
||||||
|
let (_directory, sessions, cookie) = due_session(2);
|
||||||
|
let heimdall = ScriptedHeimdall::answering(vec![
|
||||||
|
Reply::Receipt { revision: 1, claim: "claim-1" },
|
||||||
|
Reply::Timeout,
|
||||||
|
]);
|
||||||
|
pass(&sessions, &heimdall).await;
|
||||||
|
assert!(!is_live(&sessions, &cookie).await);
|
||||||
|
pass(&sessions, &heimdall).await;
|
||||||
|
assert_eq!(heimdall.calls().len(), 1, "a revoked session is not offered again");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_receipt_for_another_session_or_account_revokes_the_local_session() {
|
||||||
|
for reply in [Reply::OtherSession, Reply::OtherAccount] {
|
||||||
|
let (_directory, sessions, cookie) = due_session(1);
|
||||||
|
let heimdall = ScriptedHeimdall::answering(vec![reply]);
|
||||||
|
pass(&sessions, &heimdall).await;
|
||||||
|
assert!(!is_live(&sessions, &cookie).await);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_heimdall_denial_revokes_the_session_and_it_is_not_offered_again() {
|
||||||
|
let (_directory, sessions, cookie) = due_session(1);
|
||||||
|
let heimdall = ScriptedHeimdall::answering(vec![Reply::Deny, Reply::Timeout]);
|
||||||
|
pass(&sessions, &heimdall).await;
|
||||||
|
assert!(!is_live(&sessions, &cookie).await);
|
||||||
|
pass(&sessions, &heimdall).await;
|
||||||
|
assert_eq!(heimdall.calls().len(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_local_refusal_logs_the_clause_that_fired() {
|
||||||
|
let (_directory, sessions, _cookie) = due_session(2);
|
||||||
|
let heimdall = ScriptedHeimdall::answering(vec![Reply::Receipt {
|
||||||
|
revision: 1,
|
||||||
|
claim: "claim-1",
|
||||||
|
}]);
|
||||||
|
let captured = Captured::default();
|
||||||
|
let subscriber = tracing_subscriber::fmt()
|
||||||
|
.with_writer(captured.clone())
|
||||||
|
.with_ansi(false)
|
||||||
|
.finish();
|
||||||
|
let _guard = tracing::subscriber::set_default(subscriber);
|
||||||
|
pass(&sessions, &heimdall).await;
|
||||||
|
let logged = String::from_utf8(captured.0.lock().unwrap().clone()).unwrap();
|
||||||
|
assert!(
|
||||||
|
logged.contains("refresh receipt revision went backwards"),
|
||||||
|
"{logged}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_receipt_whose_keys_were_unavailable_is_kept_and_applied_on_the_next_pass() {
|
||||||
|
let (_directory, sessions, cookie) = due_session(1);
|
||||||
|
let heimdall = ScriptedHeimdall::answering(vec![
|
||||||
|
Reply::Receipt { revision: 1, claim: "claim-1" },
|
||||||
|
Reply::Timeout,
|
||||||
|
])
|
||||||
|
.verifying(vec![Verdict::Unavailable]);
|
||||||
|
let mut unverified = HashMap::new();
|
||||||
|
refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap();
|
||||||
|
assert!(is_live(&sessions, &cookie).await, "unavailable keys do not revoke");
|
||||||
|
assert_eq!(unverified.len(), 1);
|
||||||
|
refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap();
|
||||||
|
assert_eq!(heimdall.calls().len(), 1, "the spent claim is not sent again");
|
||||||
|
assert_eq!(heimdall.verifications(), 2);
|
||||||
|
assert!(unverified.is_empty(), "an applied receipt is not kept");
|
||||||
|
assert!(is_live(&sessions, &cookie).await);
|
||||||
|
// The applied receipt's claim is the one the next refresh spends.
|
||||||
|
refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap();
|
||||||
|
assert_eq!(heimdall.calls()[1].0, "claim-1");
|
||||||
|
assert_eq!(heimdall.verifications(), 2, "the receipt was applied once");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_receipt_that_positively_fails_verification_revokes_and_is_not_kept() {
|
||||||
|
let (_directory, sessions, cookie) = due_session(1);
|
||||||
|
let heimdall = ScriptedHeimdall::answering(vec![
|
||||||
|
Reply::Receipt { revision: 1, claim: "claim-1" },
|
||||||
|
Reply::Timeout,
|
||||||
|
])
|
||||||
|
.verifying(vec![Verdict::Invalid]);
|
||||||
|
let mut unverified = HashMap::new();
|
||||||
|
refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap();
|
||||||
|
assert!(!is_live(&sessions, &cookie).await);
|
||||||
|
assert!(unverified.is_empty());
|
||||||
|
refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap();
|
||||||
|
assert_eq!(heimdall.calls().len(), 1);
|
||||||
|
assert_eq!(heimdall.verifications(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_kept_receipt_for_a_session_that_is_gone_is_dropped() {
|
||||||
|
let (_directory, sessions, cookie) = due_session(1);
|
||||||
|
let heimdall = ScriptedHeimdall::answering(vec![Reply::Receipt {
|
||||||
|
revision: 1,
|
||||||
|
claim: "claim-1",
|
||||||
|
}])
|
||||||
|
.verifying(vec![Verdict::Unavailable]);
|
||||||
|
let mut unverified = HashMap::new();
|
||||||
|
refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap();
|
||||||
|
assert_eq!(unverified.len(), 1);
|
||||||
|
let cookie_hash = unverified.keys().next().unwrap().clone();
|
||||||
|
sessions.lock().await.revoke_cookie_hash(&cookie_hash).unwrap();
|
||||||
|
refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap();
|
||||||
|
assert!(unverified.is_empty());
|
||||||
|
assert!(!is_live(&sessions, &cookie).await);
|
||||||
|
assert_eq!(heimdall.verifications(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_session_that_moved_while_refreshing_is_not_revoked() {
|
||||||
|
let (_directory, sessions, cookie) = due_session(1);
|
||||||
|
let mut heimdall = ScriptedHeimdall::answering(vec![Reply::Receipt {
|
||||||
|
revision: 1,
|
||||||
|
claim: "claim-1",
|
||||||
|
}]);
|
||||||
|
heimdall.moving = Some(sessions.clone());
|
||||||
|
pass(&sessions, &heimdall).await;
|
||||||
|
assert!(is_live(&sessions, &cookie).await);
|
||||||
|
// The newer state wins: the next refresh spends its claim, not the
|
||||||
|
// stale receipt's.
|
||||||
|
heimdall.moving = None;
|
||||||
|
heimdall.replies.lock().unwrap().push_back(Reply::Timeout);
|
||||||
|
pass(&sessions, &heimdall).await;
|
||||||
|
assert_eq!(heimdall.calls()[1].0, "claim-moved");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_receipt_with_a_higher_revision_is_applied() {
|
||||||
|
let (_directory, sessions, cookie) = due_session(1);
|
||||||
|
let heimdall = ScriptedHeimdall::answering(vec![
|
||||||
|
Reply::Receipt { revision: 2, claim: "claim-1" },
|
||||||
|
Reply::Receipt { revision: 1, claim: "claim-2" },
|
||||||
|
]);
|
||||||
|
pass(&sessions, &heimdall).await;
|
||||||
|
assert!(is_live(&sessions, &cookie).await);
|
||||||
|
// The session now sits at revision 2, so a revision-1 receipt is
|
||||||
|
// backwards.
|
||||||
|
pass(&sessions, &heimdall).await;
|
||||||
|
assert_eq!(heimdall.calls()[1].0, "claim-1");
|
||||||
|
assert!(!is_live(&sessions, &cookie).await);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Lets the loop under test run everything that is ready, without moving
|
||||||
|
/// the paused clock.
|
||||||
|
async fn settle() {
|
||||||
|
for _ in 0..16 {
|
||||||
|
tokio::task::yield_now().await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(start_paused = true)]
|
||||||
|
async fn the_refresh_loop_runs_a_pass_every_sixty_seconds_and_keeps_going() {
|
||||||
|
let (_directory, sessions, _cookie) = due_session(1);
|
||||||
|
let heimdall = ScriptedHeimdall::answering((0..64).map(|_| Reply::Timeout).collect());
|
||||||
|
let observed = async {
|
||||||
|
settle().await;
|
||||||
|
assert_eq!(heimdall.calls().len(), 1, "the first pass runs at once");
|
||||||
|
tokio::time::advance(Duration::from_millis(59_999)).await;
|
||||||
|
settle().await;
|
||||||
|
assert_eq!(heimdall.calls().len(), 1, "no pass before sixty seconds");
|
||||||
|
tokio::time::advance(Duration::from_millis(1)).await;
|
||||||
|
settle().await;
|
||||||
|
assert_eq!(heimdall.calls().len(), 2, "the second pass at sixty seconds");
|
||||||
|
for passes in 3..=12 {
|
||||||
|
tokio::time::advance(Duration::from_secs(60)).await;
|
||||||
|
settle().await;
|
||||||
|
assert_eq!(heimdall.calls().len(), passes);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
tokio::select! {
|
||||||
|
ran = run_refresh_loop(&sessions, &heimdall) => panic!("the loop returned: {ran:?}"),
|
||||||
|
() = observed => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A refresh receipt verified by the real client against `issuer_url`,
|
||||||
|
/// whose key-set fetch fails. Returns whether the session stayed live,
|
||||||
|
/// how many receipts were kept, and the log the pass wrote.
|
||||||
|
async fn pass_through_real_verification(issuer_url: &str) -> (bool, usize, String) {
|
||||||
|
let (_directory, sessions, cookie) = due_session(1);
|
||||||
|
let client = HeimdallClient::fixture().with_issuer(issuer_url);
|
||||||
|
let token = heimdall::test_issuer::signed_token(issuer_url);
|
||||||
|
let heimdall = ScriptedHeimdall::answering(vec![Reply::Receipt {
|
||||||
|
revision: 1,
|
||||||
|
claim: "claim-1",
|
||||||
|
}])
|
||||||
|
.verifying_for_real(client, token);
|
||||||
|
let captured = Captured::default();
|
||||||
|
let subscriber = tracing_subscriber::fmt()
|
||||||
|
.with_writer(captured.clone())
|
||||||
|
.with_ansi(false)
|
||||||
|
.finish();
|
||||||
|
let _guard = tracing::subscriber::set_default(subscriber);
|
||||||
|
let mut unverified = HashMap::new();
|
||||||
|
refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap();
|
||||||
|
let logged = String::from_utf8(captured.0.lock().unwrap().clone()).unwrap();
|
||||||
|
(is_live(&sessions, &cookie).await, unverified.len(), logged)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_key_fetch_failure_in_the_real_verification_keeps_the_session_and_the_receipt() {
|
||||||
|
let failing = heimdall::test_issuer::Issuer::start(heimdall::test_issuer::Answer::ServerError)
|
||||||
|
.await;
|
||||||
|
for issuer_url in [heimdall::test_issuer::Issuer::closed_url(), failing.url.clone()] {
|
||||||
|
let (live, kept, logged) = pass_through_real_verification(&issuer_url).await;
|
||||||
|
assert!(live, "{issuer_url}: a key-fetch failure signed the session out");
|
||||||
|
assert_eq!(kept, 1, "{issuer_url}: the spent receipt was not kept");
|
||||||
|
assert!(logged.contains("could not be verified yet"), "{logged}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn the_unverified_warning_names_the_error_class_and_no_url() {
|
||||||
|
let canary = format!("{}/canary-q7x1", heimdall::test_issuer::Issuer::closed_url());
|
||||||
|
let (_, _, logged) = pass_through_real_verification(&canary).await;
|
||||||
|
assert!(logged.contains("could not connect"), "{logged}");
|
||||||
|
for leaked in [canary.as_str(), "canary-q7x1", "127.0.0.1", "jwks.json"] {
|
||||||
|
assert!(!logged.contains(leaked), "{leaked} leaked into the log: {logged}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
204
crates/ghostlight-dungeon/src/state_layout.rs
Normal file
|
|
@ -0,0 +1,204 @@
|
||||||
|
//! The admitted state layout: every declared state path must be a direct,
|
||||||
|
//! single-linked regular file or directory before anything is written to it.
|
||||||
|
|
||||||
|
use anyhow::{Context, bail, ensure};
|
||||||
|
use std::{
|
||||||
|
fs,
|
||||||
|
path::{Path, PathBuf},
|
||||||
|
};
|
||||||
|
|
||||||
|
/// The stores one timeline owns, each proved direct before it is opened.
|
||||||
|
pub(crate) const TIMELINE_STORES: [&str; 3] = ["world.cc", "controller-work.cc", "play-turn-v1.cc"];
|
||||||
|
|
||||||
|
fn default_runtime_root() -> PathBuf {
|
||||||
|
#[cfg(windows)]
|
||||||
|
{
|
||||||
|
PathBuf::from(r"F:\GameCult\GhostlightDungeon")
|
||||||
|
}
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
{
|
||||||
|
PathBuf::from("/var/lib/gamecult/ghostlight-dungeon")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn admitted_runtime_root(binding: Option<PathBuf>) -> anyhow::Result<PathBuf> {
|
||||||
|
let Some(binding) = binding else {
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
bail!("--state-root is mandatory for the managed Linux runtime");
|
||||||
|
#[cfg(not(target_os = "linux"))]
|
||||||
|
return Ok(default_runtime_root());
|
||||||
|
};
|
||||||
|
ensure!(binding.is_absolute(), "state-root binding is not absolute");
|
||||||
|
let metadata = fs::symlink_metadata(&binding)
|
||||||
|
.with_context(|| format!("inspecting state-root binding {}", binding.display()))?;
|
||||||
|
ensure!(
|
||||||
|
metadata.is_dir() && !metadata.file_type().is_symlink(),
|
||||||
|
"state-root binding is not a direct directory"
|
||||||
|
);
|
||||||
|
let canonical = fs::canonicalize(&binding)
|
||||||
|
.with_context(|| format!("canonicalizing state-root binding {}", binding.display()))?;
|
||||||
|
ensure!(
|
||||||
|
canonical == binding,
|
||||||
|
"state-root binding is indirect or non-canonical"
|
||||||
|
);
|
||||||
|
Ok(binding)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ensure_direct_directory(path: &Path, label: &str) -> anyhow::Result<()> {
|
||||||
|
match fs::symlink_metadata(path) {
|
||||||
|
Ok(_) => {}
|
||||||
|
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||||
|
fs::create_dir(path)
|
||||||
|
.with_context(|| format!("creating direct {label} {}", path.display()))?;
|
||||||
|
}
|
||||||
|
Err(error) => return Err(error).with_context(|| format!("inspecting {label}")),
|
||||||
|
}
|
||||||
|
let metadata = fs::symlink_metadata(path)
|
||||||
|
.with_context(|| format!("inspecting {label} {}", path.display()))?;
|
||||||
|
ensure!(
|
||||||
|
metadata.is_dir() && !metadata.file_type().is_symlink(),
|
||||||
|
"{label} is indirect or not a directory"
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn prepare_admitted_state_layout(runtime_root: &Path) -> anyhow::Result<()> {
|
||||||
|
let rebound = admitted_runtime_root(Some(runtime_root.to_owned()))?;
|
||||||
|
ensure!(
|
||||||
|
rebound == runtime_root,
|
||||||
|
"state-root binding changed after process-write-lease admission"
|
||||||
|
);
|
||||||
|
let service_root = runtime_root.join("service");
|
||||||
|
ensure_direct_directory(&service_root, "service state directory")?;
|
||||||
|
ensure_direct_directory(&runtime_root.join("timelines"), "timelines directory")?;
|
||||||
|
ensure_direct_directory(
|
||||||
|
&runtime_root.join(crate::vaults::SNAPSHOT_DIRECTORY),
|
||||||
|
"vault snapshot directory",
|
||||||
|
)?;
|
||||||
|
for path in [
|
||||||
|
runtime_root.join("catalog.cc"),
|
||||||
|
service_root.join("app-sessions-v2.cc"),
|
||||||
|
] {
|
||||||
|
require_direct_state_file_or_absent(&path)?;
|
||||||
|
require_direct_state_file_or_absent(&sibling_state_lock_path(&path))?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Proves a timeline's stores direct before it is opened and returns its
|
||||||
|
/// directory, created if absent.
|
||||||
|
pub(crate) fn prepare_timeline_directory(
|
||||||
|
runtime_root: &Path,
|
||||||
|
directory_name: &str,
|
||||||
|
) -> anyhow::Result<PathBuf> {
|
||||||
|
let directory = runtime_root.join("timelines").join(directory_name);
|
||||||
|
ensure_direct_directory(&directory, "timeline directory")?;
|
||||||
|
for name in TIMELINE_STORES {
|
||||||
|
let path = directory.join(name);
|
||||||
|
require_direct_state_file_or_absent(&path)?;
|
||||||
|
require_direct_state_file_or_absent(&sibling_state_lock_path(&path))?;
|
||||||
|
}
|
||||||
|
Ok(directory)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn require_direct_state_file_or_absent(path: &Path) -> anyhow::Result<()> {
|
||||||
|
match fs::symlink_metadata(path) {
|
||||||
|
Ok(metadata) => {
|
||||||
|
ensure!(
|
||||||
|
metadata.is_file() && !metadata.file_type().is_symlink(),
|
||||||
|
"declared state path {} is indirect or not a regular file",
|
||||||
|
path.display()
|
||||||
|
);
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
ensure!(
|
||||||
|
std::os::unix::fs::MetadataExt::nlink(&metadata) == 1,
|
||||||
|
"declared state path {} is multiply linked",
|
||||||
|
path.display()
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
||||||
|
Err(error) => {
|
||||||
|
Err(error).with_context(|| format!("inspecting declared state path {}", path.display()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sibling_state_lock_path(path: &Path) -> PathBuf {
|
||||||
|
let mut name = path
|
||||||
|
.file_name()
|
||||||
|
.map(|value| value.to_os_string())
|
||||||
|
.unwrap_or_else(|| "state.cc".into());
|
||||||
|
name.push(".lock");
|
||||||
|
path.with_file_name(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
#[test]
|
||||||
|
fn managed_linux_runtime_requires_the_admitted_state_root_binding() {
|
||||||
|
assert!(admitted_runtime_root(None).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn admitted_state_root_must_name_the_direct_canonical_directory() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let root = fs::canonicalize(directory.path()).unwrap();
|
||||||
|
assert_eq!(admitted_runtime_root(Some(root.clone())).unwrap(), root);
|
||||||
|
assert!(admitted_runtime_root(Some(directory.path().join("missing"))).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn post_lease_state_layout_creates_only_the_direct_declared_directories() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let root = fs::canonicalize(directory.path()).unwrap();
|
||||||
|
prepare_admitted_state_layout(&root).unwrap();
|
||||||
|
for name in ["service", "timelines"] {
|
||||||
|
let metadata = fs::symlink_metadata(root.join(name)).unwrap();
|
||||||
|
assert!(metadata.is_dir());
|
||||||
|
assert!(!metadata.file_type().is_symlink());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
#[test]
|
||||||
|
fn post_lease_state_layout_rejects_symlinks_and_hardlinks() {
|
||||||
|
use std::os::unix::fs::symlink;
|
||||||
|
|
||||||
|
let symlink_directory = tempfile::tempdir().unwrap();
|
||||||
|
let symlink_root = fs::canonicalize(symlink_directory.path()).unwrap();
|
||||||
|
let target = symlink_root.join("other.cc");
|
||||||
|
fs::write(&target, b"not-catalog").unwrap();
|
||||||
|
symlink(&target, symlink_root.join("catalog.cc")).unwrap();
|
||||||
|
assert!(prepare_admitted_state_layout(&symlink_root).is_err());
|
||||||
|
|
||||||
|
let hardlink_directory = tempfile::tempdir().unwrap();
|
||||||
|
let hardlink_root = fs::canonicalize(hardlink_directory.path()).unwrap();
|
||||||
|
let target = hardlink_root.join("other.cc");
|
||||||
|
fs::write(&target, b"not-catalog").unwrap();
|
||||||
|
fs::hard_link(&target, hardlink_root.join("catalog.cc")).unwrap();
|
||||||
|
assert!(prepare_admitted_state_layout(&hardlink_root).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A timeline's own stores get the same proof as the service's, before the
|
||||||
|
/// timeline is opened: a symlink standing in for its play-turn store is
|
||||||
|
/// refused.
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
#[test]
|
||||||
|
fn a_symlinked_timeline_store_is_refused() {
|
||||||
|
use std::os::unix::fs::symlink;
|
||||||
|
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let root = fs::canonicalize(directory.path()).unwrap();
|
||||||
|
prepare_admitted_state_layout(&root).unwrap();
|
||||||
|
let name = "00000000-0000-4000-8000-000000000001";
|
||||||
|
let timeline = prepare_timeline_directory(&root, name).unwrap();
|
||||||
|
let target = root.join("other.cc");
|
||||||
|
fs::write(&target, b"not-play-turn").unwrap();
|
||||||
|
symlink(&target, timeline.join("play-turn-v1.cc")).unwrap();
|
||||||
|
assert!(prepare_timeline_directory(&root, name).is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
120
crates/ghostlight-dungeon/src/timelines.rs
Normal file
|
|
@ -0,0 +1,120 @@
|
||||||
|
//! Many timelines in one daemon.
|
||||||
|
//!
|
||||||
|
//! Each timeline is its own kernel store with its own mailbox, play table and
|
||||||
|
//! controller work; every one shares the single routed inference port and the
|
||||||
|
//! one concurrency pool. A timeline opens on first use and stays warm.
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
catalog::timeline_directory_name,
|
||||||
|
play::PlayTable,
|
||||||
|
state_layout::prepare_timeline_directory,
|
||||||
|
};
|
||||||
|
use ghostlight::{
|
||||||
|
ControllerModels, ControllerPort, ControllerRunner, InferencePort, PersonaLane, WorldMailbox,
|
||||||
|
open_controller_work,
|
||||||
|
};
|
||||||
|
use anyhow::Context;
|
||||||
|
use std::{collections::HashMap, path::PathBuf, sync::Arc};
|
||||||
|
use tokio::sync::{Mutex, Semaphore, broadcast, mpsc};
|
||||||
|
|
||||||
|
/// What every timeline shares: the one inference port all lanes route through,
|
||||||
|
/// the model each lane runs on, and the concurrency pool sized to the
|
||||||
|
/// connector's quota.
|
||||||
|
pub(crate) struct Shared {
|
||||||
|
pub(crate) inference: Arc<dyn InferencePort>,
|
||||||
|
pub(crate) models: ControllerModels,
|
||||||
|
pub(crate) play_model: String,
|
||||||
|
pub(crate) permits: Arc<Semaphore>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One opened timeline.
|
||||||
|
pub(crate) struct TimelineHost {
|
||||||
|
pub(crate) world: WorldMailbox,
|
||||||
|
pub(crate) controllers: ControllerRunner,
|
||||||
|
pub(crate) play: Arc<PlayTable>,
|
||||||
|
/// Pulsed whenever this timeline's turn changes; the stream wakes on it.
|
||||||
|
pub(crate) changes: broadcast::Sender<()>,
|
||||||
|
/// Held while a run-ahead sweep runs: one at a time per timeline.
|
||||||
|
pub(crate) sweeping: Mutex<()>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct Timelines {
|
||||||
|
root: PathBuf,
|
||||||
|
shared: Shared,
|
||||||
|
hosts: Mutex<HashMap<String, Arc<TimelineHost>>>,
|
||||||
|
fatal: mpsc::UnboundedSender<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Timelines {
|
||||||
|
pub(crate) fn new(root: PathBuf, shared: Shared, fatal: mpsc::UnboundedSender<String>) -> Self {
|
||||||
|
Self {
|
||||||
|
root,
|
||||||
|
shared,
|
||||||
|
hosts: Mutex::new(HashMap::new()),
|
||||||
|
fatal,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn shared(&self) -> &Shared {
|
||||||
|
&self.shared
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The host for `id`, opened on first use. Refuses an id that is not
|
||||||
|
/// exactly `timeline:<canonical uuid>`.
|
||||||
|
pub(crate) async fn host(&self, id: &str) -> anyhow::Result<Arc<TimelineHost>> {
|
||||||
|
let name = timeline_directory_name(id).context("timeline id is not canonical")?;
|
||||||
|
let mut hosts = self.hosts.lock().await;
|
||||||
|
if let Some(host) = hosts.get(id) {
|
||||||
|
return Ok(host.clone());
|
||||||
|
}
|
||||||
|
let directory = prepare_timeline_directory(&self.root, &name)?;
|
||||||
|
let (world, owner) = WorldMailbox::open(directory.join("world.cc"))?;
|
||||||
|
let fatal = self.fatal.clone();
|
||||||
|
let label = id.to_owned();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let _ = owner.await;
|
||||||
|
let _ = fatal.send(format!("world owner of {label} stopped while serving"));
|
||||||
|
});
|
||||||
|
let work = open_controller_work(directory.join("controller-work.cc"))?;
|
||||||
|
let controllers = ControllerRunner::open(
|
||||||
|
world.clone(),
|
||||||
|
self.shared.inference.clone(),
|
||||||
|
work,
|
||||||
|
self.shared.models.clone(),
|
||||||
|
)?;
|
||||||
|
let personas = PersonaLane::new(
|
||||||
|
ControllerPort::new(world.clone()),
|
||||||
|
self.shared.inference.clone(),
|
||||||
|
self.shared.models.projector.clone(),
|
||||||
|
self.shared.models.persona.clone(),
|
||||||
|
)?;
|
||||||
|
let play = PlayTable::new(
|
||||||
|
world.clone(),
|
||||||
|
personas,
|
||||||
|
self.shared.inference.clone(),
|
||||||
|
self.shared.play_model.clone(),
|
||||||
|
self.shared.permits.clone(),
|
||||||
|
directory.join("play-turn-v1.cc"),
|
||||||
|
)?;
|
||||||
|
let (changes, _) = broadcast::channel(16);
|
||||||
|
let host = Arc::new(TimelineHost {
|
||||||
|
world,
|
||||||
|
controllers,
|
||||||
|
play: Arc::new(play),
|
||||||
|
changes,
|
||||||
|
sweeping: Mutex::new(()),
|
||||||
|
});
|
||||||
|
hosts.insert(id.to_owned(), host.clone());
|
||||||
|
Ok(host)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every timeline opened so far; readiness probes these.
|
||||||
|
pub(crate) async fn opened(&self) -> Vec<(String, Arc<TimelineHost>)> {
|
||||||
|
self.hosts
|
||||||
|
.lock()
|
||||||
|
.await
|
||||||
|
.iter()
|
||||||
|
.map(|(id, host)| (id.clone(), host.clone()))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
}
|
||||||
242
crates/ghostlight-dungeon/src/turn_log.rs
Normal file
|
|
@ -0,0 +1,242 @@
|
||||||
|
//! The turn log: what the player was shown, turn by turn, kept for as long as
|
||||||
|
//! the timeline lives.
|
||||||
|
//!
|
||||||
|
//! The kernel journal records what happened in the world, not the prose the
|
||||||
|
//! storyteller wrote about it, and the play row holds only the current turn.
|
||||||
|
//! So the narration a player read exists in one place until the next turn
|
||||||
|
//! replaces it. This log is where it stays. It sits next to the timeline's
|
||||||
|
//! other state and is written by `PlayTable` from the row the screen is drawn
|
||||||
|
//! from, right after that row is committed, so an entry can never say
|
||||||
|
//! something the screen did not. It is append-only: nothing here edits or
|
||||||
|
//! deletes an entry, and a Retry is a new entry that names the one it retries.
|
||||||
|
|
||||||
|
use anyhow::{Context, bail, ensure};
|
||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::{collections::HashMap, path::Path};
|
||||||
|
|
||||||
|
const TYPE: &str = "ghostlight.dungeon_turn_log.v1";
|
||||||
|
|
||||||
|
/// How a submission ended, as the player was told.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub(crate) enum TurnStatus {
|
||||||
|
/// The turn closed and narrated.
|
||||||
|
Committed,
|
||||||
|
/// The world refused an act of the turn; `refusal` holds the line.
|
||||||
|
Refused,
|
||||||
|
/// The turn died on its model; `fault` holds the line shown.
|
||||||
|
Faulted,
|
||||||
|
/// The storyteller asked a question and is waiting; `question` holds it.
|
||||||
|
Asked,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One submission and what it produced. `seq` is its place in the log, from 1.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub(crate) struct LogEntry {
|
||||||
|
pub(crate) seq: u64,
|
||||||
|
pub(crate) turn_id: String,
|
||||||
|
/// Which submission of that turn this is: 1 opens it, each answer adds one.
|
||||||
|
pub(crate) submission: u32,
|
||||||
|
/// The player's text exactly as sent.
|
||||||
|
pub(crate) text: String,
|
||||||
|
pub(crate) narration: Option<String>,
|
||||||
|
pub(crate) question: Option<String>,
|
||||||
|
pub(crate) refusal: Option<String>,
|
||||||
|
pub(crate) fault: Option<String>,
|
||||||
|
pub(crate) status: TurnStatus,
|
||||||
|
/// The world revision the entry rests on, or `None` when the kernel could
|
||||||
|
/// not be read at the moment the entry was written.
|
||||||
|
pub(crate) world_revision: Option<u64>,
|
||||||
|
/// The entry this one retries.
|
||||||
|
pub(crate) retry_of: Option<u64>,
|
||||||
|
pub(crate) recorded_at: DateTime<Utc>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An entry before it has a place in the log.
|
||||||
|
pub(crate) struct NewEntry {
|
||||||
|
pub(crate) turn_id: String,
|
||||||
|
pub(crate) submission: u32,
|
||||||
|
pub(crate) text: String,
|
||||||
|
pub(crate) narration: Option<String>,
|
||||||
|
pub(crate) question: Option<String>,
|
||||||
|
pub(crate) refusal: Option<String>,
|
||||||
|
pub(crate) fault: Option<String>,
|
||||||
|
pub(crate) status: TurnStatus,
|
||||||
|
pub(crate) world_revision: Option<u64>,
|
||||||
|
pub(crate) retry_of: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A page of the log, oldest first, newest last.
|
||||||
|
pub(crate) struct Page {
|
||||||
|
pub(crate) entries: Vec<(LogEntry, Option<u64>)>,
|
||||||
|
/// Pass as `before` to read the page of older entries; `None` at the start.
|
||||||
|
pub(crate) older: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct TurnLog {
|
||||||
|
store: OwnedRedbMessagePackBackingStore,
|
||||||
|
/// Every entry, `entries[n]` having `seq == n + 1`.
|
||||||
|
entries: Vec<LogEntry>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn key_of(seq: u64) -> String {
|
||||||
|
format!("{seq:012}")
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TurnLog {
|
||||||
|
pub(crate) fn open(path: impl AsRef<Path>) -> anyhow::Result<Self> {
|
||||||
|
let store = OwnedRedbMessagePackBackingStore::new(path.as_ref())?;
|
||||||
|
store.validate_path_identity().context("turn log path identity is invalid")?;
|
||||||
|
let mut entries = Vec::new();
|
||||||
|
for row in store.pull_all()? {
|
||||||
|
ensure!(row.r#type == TYPE, "turn log holds a foreign record");
|
||||||
|
let entry: LogEntry = rmp_serde::from_slice(&row.payload).context("a turn log entry did not decode")?;
|
||||||
|
ensure!(row.key == key_of(entry.seq), "a turn log entry sits under the wrong key");
|
||||||
|
entries.push(entry);
|
||||||
|
}
|
||||||
|
entries.sort_by_key(|entry| entry.seq);
|
||||||
|
for (index, entry) in entries.iter().enumerate() {
|
||||||
|
if entry.seq != index as u64 + 1 {
|
||||||
|
bail!("the turn log has a gap before entry {}", entry.seq);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Self { store, entries })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn contains(&self, seq: u64) -> bool {
|
||||||
|
seq >= 1 && seq <= self.entries.len() as u64
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn recorded(&self, turn_id: &str, submission: u32) -> bool {
|
||||||
|
self.entries
|
||||||
|
.iter()
|
||||||
|
.rev()
|
||||||
|
.any(|entry| entry.turn_id == turn_id && entry.submission == submission)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Appends `new` unless that turn's submission is already recorded.
|
||||||
|
/// Returns the new entry's `seq`, or `None` when it was already there.
|
||||||
|
pub(crate) fn record(&mut self, new: NewEntry) -> anyhow::Result<Option<u64>> {
|
||||||
|
if self.recorded(&new.turn_id, new.submission) {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
if let Some(target) = new.retry_of {
|
||||||
|
ensure!(self.contains(target), "a retry names an entry the log does not hold");
|
||||||
|
}
|
||||||
|
let seq = self.entries.len() as u64 + 1;
|
||||||
|
let entry = LogEntry {
|
||||||
|
seq,
|
||||||
|
turn_id: new.turn_id,
|
||||||
|
submission: new.submission,
|
||||||
|
text: new.text,
|
||||||
|
narration: new.narration,
|
||||||
|
question: new.question,
|
||||||
|
refusal: new.refusal,
|
||||||
|
fault: new.fault,
|
||||||
|
status: new.status,
|
||||||
|
world_revision: new.world_revision,
|
||||||
|
retry_of: new.retry_of,
|
||||||
|
recorded_at: Utc::now(),
|
||||||
|
};
|
||||||
|
let row = CultCacheEnvelope {
|
||||||
|
key: key_of(seq),
|
||||||
|
r#type: TYPE.into(),
|
||||||
|
payload: rmp_serde::to_vec_named(&entry)?,
|
||||||
|
stored_at: entry.recorded_at.to_rfc3339(),
|
||||||
|
schema_id: Some(TYPE.into()),
|
||||||
|
};
|
||||||
|
self.store.validate_path_identity().context("turn log ownership was lost")?;
|
||||||
|
if !self.store.compare_and_swap_batch(&[], vec![row])? {
|
||||||
|
bail!("turn log entry {seq} already exists on disk");
|
||||||
|
}
|
||||||
|
self.entries.push(entry);
|
||||||
|
Ok(Some(seq))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Up to `limit` entries older than `before` (the newest when `None`),
|
||||||
|
/// each with the `seq` of the entry that retried it, if one did.
|
||||||
|
pub(crate) fn page(&self, before: Option<u64>, limit: usize) -> Page {
|
||||||
|
let end = before.map_or(self.entries.len(), |before| (before.saturating_sub(1) as usize).min(self.entries.len()));
|
||||||
|
let start = end.saturating_sub(limit.max(1));
|
||||||
|
let retried_by: HashMap<u64, u64> = self
|
||||||
|
.entries
|
||||||
|
.iter()
|
||||||
|
.rev()
|
||||||
|
.filter_map(|entry| entry.retry_of.map(|target| (target, entry.seq)))
|
||||||
|
.collect();
|
||||||
|
let entries = self.entries[start..end]
|
||||||
|
.iter()
|
||||||
|
.map(|entry| (entry.clone(), retried_by.get(&entry.seq).copied()))
|
||||||
|
.collect();
|
||||||
|
Page { entries, older: (start > 0).then_some(start as u64 + 1) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn new(turn: &str, submission: u32, text: &str) -> NewEntry {
|
||||||
|
NewEntry {
|
||||||
|
turn_id: turn.into(),
|
||||||
|
submission,
|
||||||
|
text: text.into(),
|
||||||
|
narration: Some(format!("story of {text}")),
|
||||||
|
question: None,
|
||||||
|
refusal: None,
|
||||||
|
fault: None,
|
||||||
|
status: TurnStatus::Committed,
|
||||||
|
world_revision: Some(7),
|
||||||
|
retry_of: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn entries_append_page_newest_last_and_survive_a_reopen() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let path = directory.path().join("turn-log-v1.cc");
|
||||||
|
{
|
||||||
|
let mut log = TurnLog::open(&path).unwrap();
|
||||||
|
for n in 1..=5 {
|
||||||
|
assert_eq!(log.record(new(&format!("t{n}"), 1, &format!("say {n}"))).unwrap(), Some(n));
|
||||||
|
}
|
||||||
|
assert_eq!(log.record(new("t3", 1, "say 3 again")).unwrap(), None, "a recorded submission is never rewritten");
|
||||||
|
let newest = log.page(None, 2);
|
||||||
|
assert_eq!(newest.entries.iter().map(|(e, _)| e.seq).collect::<Vec<_>>(), [4, 5]);
|
||||||
|
assert_eq!(newest.older, Some(4));
|
||||||
|
let older = log.page(newest.older, 2);
|
||||||
|
assert_eq!(older.entries.iter().map(|(e, _)| e.seq).collect::<Vec<_>>(), [2, 3]);
|
||||||
|
let oldest = log.page(older.older, 2);
|
||||||
|
assert_eq!(oldest.entries.iter().map(|(e, _)| e.seq).collect::<Vec<_>>(), [1]);
|
||||||
|
assert_eq!(oldest.older, None);
|
||||||
|
}
|
||||||
|
let log = TurnLog::open(&path).unwrap();
|
||||||
|
let all = log.page(None, 50);
|
||||||
|
assert_eq!(all.entries.len(), 5);
|
||||||
|
assert_eq!(all.entries[2].0.text, "say 3", "the first write stands");
|
||||||
|
assert_eq!(all.entries[2].0.narration.as_deref(), Some("story of say 3"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_retry_is_a_new_entry_and_the_old_one_reads_as_superseded() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let mut log = TurnLog::open(directory.path().join("turn-log-v1.cc")).unwrap();
|
||||||
|
let mut faulted = new("t1", 1, "I knock");
|
||||||
|
faulted.status = TurnStatus::Faulted;
|
||||||
|
faulted.narration = None;
|
||||||
|
faulted.fault = Some("the storyteller lost the thread".into());
|
||||||
|
log.record(faulted).unwrap();
|
||||||
|
let mut retry = new("t2", 1, "I knock");
|
||||||
|
retry.retry_of = Some(1);
|
||||||
|
log.record(retry).unwrap();
|
||||||
|
let page = log.page(None, 10);
|
||||||
|
assert_eq!(page.entries[0].0.status, TurnStatus::Faulted, "the old entry stays as it was");
|
||||||
|
assert_eq!(page.entries[0].1, Some(2), "and reads as superseded by the retry");
|
||||||
|
assert_eq!(page.entries[1].1, None);
|
||||||
|
let mut bad = new("t3", 1, "x");
|
||||||
|
bad.retry_of = Some(99);
|
||||||
|
assert!(log.record(bad).is_err(), "a retry must name an entry the log holds");
|
||||||
|
}
|
||||||
|
}
|
||||||
249
crates/ghostlight-dungeon/src/vaults.rs
Normal file
|
|
@ -0,0 +1,249 @@
|
||||||
|
//! The production vault catalog: the profiles production serves, over the
|
||||||
|
//! snapshots an operator import left in the store.
|
||||||
|
//!
|
||||||
|
//! The daemon never reads a vault directory. `VaultSnapshot::build` is the
|
||||||
|
//! only reader of one, and it runs in the `import-vault` command; what lives
|
||||||
|
//! here is a read of the store the import wrote: which snapshot a profile last
|
||||||
|
//! produced, and that snapshot's evidence.
|
||||||
|
|
||||||
|
use crate::begin::{VaultOffer, VaultSeed, Vaults};
|
||||||
|
use anyhow::{Context, bail};
|
||||||
|
use ghostlight::{
|
||||||
|
EvidenceSource, SnapshotId, VaultEra, VaultEvidenceSource, VaultError, VaultSnapshot, WorldEra,
|
||||||
|
production_eras, production_profile, production_vault_names,
|
||||||
|
};
|
||||||
|
use std::{
|
||||||
|
collections::HashMap,
|
||||||
|
path::{Path, PathBuf},
|
||||||
|
sync::{Arc, Mutex},
|
||||||
|
};
|
||||||
|
|
||||||
|
/// The snapshot store, under the state root.
|
||||||
|
pub(crate) const SNAPSHOT_DIRECTORY: &str = "snapshots";
|
||||||
|
|
||||||
|
/// The directory the host keeps its vault copies in; the importer roots every
|
||||||
|
/// production profile under it.
|
||||||
|
pub(crate) const VAULT_BASE_ENVIRONMENT: &str = "GHOSTLIGHT_VAULT_BASE";
|
||||||
|
|
||||||
|
pub(crate) struct SnapshotVaults {
|
||||||
|
store: PathBuf,
|
||||||
|
/// A snapshot's evidence for one era, loaded once: every turn's run-ahead
|
||||||
|
/// sweep asks for it again. Cache only; the era is the world's.
|
||||||
|
evidence: Mutex<HashMap<(String, String), Arc<dyn EvidenceSource>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SnapshotVaults {
|
||||||
|
pub(crate) fn new(state_root: &Path) -> Self {
|
||||||
|
Self {
|
||||||
|
store: state_root.join(SNAPSHOT_DIRECTORY),
|
||||||
|
evidence: Mutex::new(HashMap::new()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn imported(&self, profile: &str) -> Result<SnapshotId, VaultError> {
|
||||||
|
VaultSnapshot::current_id(&self.store, profile)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The evidence of `snapshot` for `era`, which withholds the era's paths; a
|
||||||
|
/// world with no era withholds nothing.
|
||||||
|
fn evidence_for(snapshot: &VaultSnapshot, era: Option<&VaultEra>) -> anyhow::Result<Arc<dyn EvidenceSource>> {
|
||||||
|
let evidence = VaultEvidenceSource::from_snapshot(snapshot, "", era.map_or(&[], |era| era.withhold))
|
||||||
|
.context("the snapshot holds no evidence")?;
|
||||||
|
Ok(Arc::new(evidence))
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Vaults for SnapshotVaults {
|
||||||
|
fn offers(&self) -> Vec<VaultOffer> {
|
||||||
|
production_vault_names()
|
||||||
|
.filter(|name| self.imported(name).is_ok())
|
||||||
|
.filter_map(|name| {
|
||||||
|
let (eras, default) = production_eras(name)?;
|
||||||
|
Some(VaultOffer {
|
||||||
|
name: name.to_owned(),
|
||||||
|
default_era: default.to_owned(),
|
||||||
|
eras: eras.iter().map(world_era).collect(),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn open(&self, profile: &str, era: Option<&str>) -> anyhow::Result<VaultSeed> {
|
||||||
|
let Some((eras, default)) = production_eras(profile) else {
|
||||||
|
bail!("vault profile `{profile}` is not one this server serves");
|
||||||
|
};
|
||||||
|
let wanted = era.unwrap_or(default);
|
||||||
|
let chosen = eras
|
||||||
|
.iter()
|
||||||
|
.find(|candidate| candidate.id == wanted)
|
||||||
|
.with_context(|| format!("vault profile `{profile}` has no era `{wanted}`"))?;
|
||||||
|
let id = self
|
||||||
|
.imported(profile)
|
||||||
|
.map_err(|_| anyhow::anyhow!("vault profile `{profile}` has not been imported"))?;
|
||||||
|
let snapshot = VaultSnapshot::load(&self.store, &id)
|
||||||
|
.map_err(|error| anyhow::anyhow!("vault profile `{profile}`: {error}"))?;
|
||||||
|
let evidence = evidence_for(&snapshot, Some(chosen))?;
|
||||||
|
self.evidence
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.insert((id.to_string(), chosen.id.to_owned()), evidence.clone());
|
||||||
|
Ok(VaultSeed {
|
||||||
|
snapshot_id: id.to_string(),
|
||||||
|
evidence,
|
||||||
|
premise: snapshot.premise(),
|
||||||
|
era: world_era(chosen),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn evidence(&self, snapshot_id: &str, era: Option<&str>) -> anyhow::Result<Arc<dyn EvidenceSource>> {
|
||||||
|
let key = (snapshot_id.to_owned(), era.unwrap_or_default().to_owned());
|
||||||
|
if let Some(held) = self.evidence.lock().unwrap().get(&key) {
|
||||||
|
return Ok(held.clone());
|
||||||
|
}
|
||||||
|
let id = SnapshotId::parse(snapshot_id).context("the snapshot id is not an id")?;
|
||||||
|
let snapshot = VaultSnapshot::load(&self.store, &id)
|
||||||
|
.map_err(|error| anyhow::anyhow!("snapshot {snapshot_id}: {error}"))?;
|
||||||
|
let name = &snapshot.profile().name;
|
||||||
|
let chosen = match era {
|
||||||
|
None => None,
|
||||||
|
Some(era) => Some(
|
||||||
|
production_eras(name)
|
||||||
|
.and_then(|(eras, _)| eras.iter().find(|candidate| candidate.id == era))
|
||||||
|
.with_context(|| format!("vault profile `{name}` has no era `{era}`"))?,
|
||||||
|
),
|
||||||
|
};
|
||||||
|
let evidence = evidence_for(&snapshot, chosen)?;
|
||||||
|
self.evidence.lock().unwrap().insert(key, evidence.clone());
|
||||||
|
Ok(evidence)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn world_era(era: &VaultEra) -> WorldEra {
|
||||||
|
WorldEra {
|
||||||
|
id: era.id.to_owned(),
|
||||||
|
label: era.label.to_owned(),
|
||||||
|
description: era.description.to_owned(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `ghostlight-dungeon import-vault --state-root PATH PROFILE`: the one reader
|
||||||
|
/// of a vault directory. Builds the production profile of `profile` rooted
|
||||||
|
/// under `$GHOSTLIGHT_VAULT_BASE`, stores the snapshot and records it as the
|
||||||
|
/// profile's current import. Prints the snapshot id.
|
||||||
|
pub(crate) fn import(state_root: &Path, profile: &str) -> anyhow::Result<String> {
|
||||||
|
let base = std::env::var_os(VAULT_BASE_ENVIRONMENT)
|
||||||
|
.map(PathBuf::from)
|
||||||
|
.with_context(|| format!("{VAULT_BASE_ENVIRONMENT} is required"))?;
|
||||||
|
let Some(profile) = production_profile(profile, &base) else {
|
||||||
|
bail!("vault profile `{profile}` is not one this server serves");
|
||||||
|
};
|
||||||
|
let store = state_root.join(SNAPSHOT_DIRECTORY);
|
||||||
|
let snapshot = VaultSnapshot::build(&profile).map_err(|error| anyhow::anyhow!("{error}"))?;
|
||||||
|
snapshot
|
||||||
|
.import_into(&store)
|
||||||
|
.map_err(|error| anyhow::anyhow!("{error}"))?;
|
||||||
|
snapshot
|
||||||
|
.record_current(&store)
|
||||||
|
.map_err(|error| anyhow::anyhow!("{error}"))?;
|
||||||
|
Ok(format!("{} notes={} id={}", profile.name, snapshot.note_count(), snapshot.id()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn write(root: &Path, relative: &str, text: &str) {
|
||||||
|
let path = root.join(relative);
|
||||||
|
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||||
|
std::fs::write(path, text).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An imported snapshot of a tiny Avatar vault under a state root.
|
||||||
|
fn imported_avatar() -> (tempfile::TempDir, SnapshotVaults, String) {
|
||||||
|
let state = tempfile::tempdir().unwrap();
|
||||||
|
let vault = tempfile::tempdir().unwrap();
|
||||||
|
write(vault.path(), "Avatar/index.md", "A river city under a spirit sky.\n");
|
||||||
|
write(vault.path(), "Avatar/Places/Harbor.md", "The harbor of the river city.\n");
|
||||||
|
let profile = production_profile("avatar", vault.path()).unwrap();
|
||||||
|
let snapshot = VaultSnapshot::build(&profile).unwrap();
|
||||||
|
let store = state.path().join(SNAPSHOT_DIRECTORY);
|
||||||
|
snapshot.import_into(&store).unwrap();
|
||||||
|
snapshot.record_current(&store).unwrap();
|
||||||
|
let id = snapshot.id().to_string();
|
||||||
|
let vaults = SnapshotVaults::new(state.path());
|
||||||
|
(state, vaults, id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The id gate keeps a stored id from naming another path: a short hex
|
||||||
|
/// string and a long non-hex one are both refused before any path is built.
|
||||||
|
#[test]
|
||||||
|
fn a_stored_snapshot_id_that_is_not_an_id_is_refused_before_a_path_is_built() {
|
||||||
|
let (_state, vaults, id) = imported_avatar();
|
||||||
|
for bad in ["abc".to_owned(), format!("../{}", &id[3..]), id.to_uppercase()] {
|
||||||
|
let error = vaults.evidence(&bad, Some("rda-return")).err().expect("refused").to_string();
|
||||||
|
assert!(error.contains("not an id"), "{bad}: {error}");
|
||||||
|
}
|
||||||
|
assert!(vaults.evidence(&id, Some("rda-return")).is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn it_lists_the_imported_profiles_and_opens_the_recorded_snapshot() {
|
||||||
|
let (_state, vaults, id) = imported_avatar();
|
||||||
|
assert_eq!(vaults.offers().iter().map(|offer| offer.name.as_str()).collect::<Vec<_>>(), ["avatar"]);
|
||||||
|
let seed = vaults.open("avatar", None).unwrap();
|
||||||
|
assert_eq!(seed.snapshot_id, id);
|
||||||
|
assert_eq!(seed.premise.as_deref(), Some("A river city under a spirit sky."));
|
||||||
|
assert_eq!(seed.era.id, "rda-return", "an omitted era is the profile's default");
|
||||||
|
assert!(vaults.evidence(&id, Some("rda-return")).is_ok());
|
||||||
|
assert!(vaults.evidence(&id, Some("no-such-era")).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_profile_never_imported_is_refused_by_name_and_so_is_a_stranger() {
|
||||||
|
let (_state, vaults, _) = imported_avatar();
|
||||||
|
let never = vaults.open("zyphos", None).err().unwrap().to_string();
|
||||||
|
assert!(never.contains("`zyphos` has not been imported"), "{never}");
|
||||||
|
let stranger = vaults.open("../avatar", None).err().unwrap().to_string();
|
||||||
|
assert!(stranger.contains("is not one this server serves"), "{stranger}");
|
||||||
|
assert!(vaults.evidence("not-an-id", Some("rda-return")).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The daemon side is a read of the store alone: with the vault directory
|
||||||
|
/// gone the profile still opens.
|
||||||
|
#[test]
|
||||||
|
fn opening_a_profile_reads_the_store_and_never_the_vault() {
|
||||||
|
let (_state, vaults, _) = imported_avatar();
|
||||||
|
// `imported_avatar` dropped its vault directory already.
|
||||||
|
assert!(vaults.open("avatar", None).is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A pre-Elysium Aetheria world never sees the Post-Elysium folder, in the
|
||||||
|
/// seed's evidence or in the evidence reopened for run-ahead; a
|
||||||
|
/// post-Elysium world does.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_pre_elysium_world_never_sees_the_post_elysium_folder() {
|
||||||
|
use ghostlight::EvidenceQuery;
|
||||||
|
let state = tempfile::tempdir().unwrap();
|
||||||
|
let vault = tempfile::tempdir().unwrap();
|
||||||
|
write(vault.path(), "AetheriaLore/Aetheria/Worldbuilding/Post-Elysium/Aether.md", "The aether answers espers.\n");
|
||||||
|
write(vault.path(), "AetheriaLore/Aetheria/Worldbuilding/Pre-Elysium/Collapse.md", "The grid fails.\n");
|
||||||
|
let snapshot = VaultSnapshot::build(&production_profile("aetheria", vault.path()).unwrap()).unwrap();
|
||||||
|
let store = state.path().join(SNAPSHOT_DIRECTORY);
|
||||||
|
snapshot.import_into(&store).unwrap();
|
||||||
|
snapshot.record_current(&store).unwrap();
|
||||||
|
let id = snapshot.id().to_string();
|
||||||
|
let vaults = SnapshotVaults::new(state.path());
|
||||||
|
let aether = EvidenceQuery { referents: vec!["Aether".into()] };
|
||||||
|
|
||||||
|
let seed = vaults.open("aetheria", None).unwrap();
|
||||||
|
assert_eq!(seed.era.id, "pre-elysium", "late Sol is the default");
|
||||||
|
assert!(seed.evidence.retrieve(&aether).await.unwrap().is_empty(), "the seed's evidence");
|
||||||
|
let reopened = vaults.evidence(&id, Some("pre-elysium")).unwrap();
|
||||||
|
assert!(reopened.retrieve(&aether).await.unwrap().is_empty(), "run-ahead's evidence");
|
||||||
|
|
||||||
|
let after = vaults.open("aetheria", Some("post-elysium")).unwrap();
|
||||||
|
assert!(!after.evidence.retrieve(&aether).await.unwrap().is_empty());
|
||||||
|
assert!(vaults.open("aetheria", Some("nowhen")).is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
27
crates/ghostlight-dungeon/tests/build_provenance.rs
Normal file
|
|
@ -0,0 +1,27 @@
|
||||||
|
use std::{fs, path::Path, process::Command};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn embedded_commit_matches_checkout_head() {
|
||||||
|
let repo_root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
|
||||||
|
let output = Command::new("git")
|
||||||
|
.args(["rev-parse", "HEAD"])
|
||||||
|
.current_dir(&repo_root)
|
||||||
|
.output()
|
||||||
|
.expect("git must be available for the provenance regression test");
|
||||||
|
let checkout_head = if output.status.success() {
|
||||||
|
String::from_utf8(output.stdout)
|
||||||
|
.expect("git commit must be UTF-8")
|
||||||
|
.trim()
|
||||||
|
.to_owned()
|
||||||
|
} else {
|
||||||
|
fs::read_to_string(repo_root.join(".ghostlight-source-commit"))
|
||||||
|
.expect("frozen source archive must carry its exact commit witness")
|
||||||
|
.trim()
|
||||||
|
.to_owned()
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
env!("GHOSTLIGHT_BUILD_COMMIT"),
|
||||||
|
checkout_head,
|
||||||
|
"the binary embedded stale Git provenance"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -54,6 +54,17 @@ pub struct ProjectorPrompt<'a> {
|
||||||
pub word_budget: usize,
|
pub word_budget: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// What the storyteller is given to narrate a human player's own view. The
|
||||||
|
/// player is not a Persona: nothing here is lived from inside them.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct NarratorPrompt<'a> {
|
||||||
|
pub player: &'a str,
|
||||||
|
pub typed_context: &'a str,
|
||||||
|
pub visible_stimulus: &'a str,
|
||||||
|
pub domain_guidance: &'a str,
|
||||||
|
pub word_budget: usize,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
pub struct PersonaPrompt<'a> {
|
pub struct PersonaPrompt<'a> {
|
||||||
pub identity: &'a str,
|
pub identity: &'a str,
|
||||||
|
|
@ -93,6 +104,31 @@ pub fn build_projector_prompt(input: &ProjectorPrompt<'_>) -> String {
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The storyteller's contract: it narrates to the player, in second person, and
|
||||||
|
/// is never the player or anyone else in the story.
|
||||||
|
pub fn build_narrator_prompt(input: &NarratorPrompt<'_>) -> String {
|
||||||
|
format!(
|
||||||
|
"<!-- membrane:{MEMBRANE_SCHEMA}:narrator -->
|
||||||
|
You are the storyteller of a world, narrating the player's present moment to the player. The player's character is {player}. Always speak to the player in the second person, present tense (\"You stand in...\"); never in the first person, and never as {player} or any other character. Anything the player said or did is the player's own, never yours: if you refer to it, quote it as theirs (\"You said...\"). Render only what the permitted context and visible stimulus establish, as a short scene: the place you stand in, who is here with you by name, each way out and where it leads, anything pressing on you, and what you could do now. Name only the people, places, and routes the context names; invent none, and do not claim what lies beyond an exit. Anything absent from the context is unknown: say so once, plainly, rather than repeating status you do not have. Do not choose actions for the player, expose field names, or claim world effects.
|
||||||
|
|
||||||
|
Domain guidance:
|
||||||
|
{guidance}
|
||||||
|
|
||||||
|
Permitted typed context:
|
||||||
|
{context}
|
||||||
|
|
||||||
|
Visible stimulus:
|
||||||
|
{stimulus}
|
||||||
|
|
||||||
|
Use at most {word_budget} words; fewer is better. Return only the narration.",
|
||||||
|
player = input.player,
|
||||||
|
guidance = input.domain_guidance,
|
||||||
|
context = input.typed_context,
|
||||||
|
stimulus = input.visible_stimulus,
|
||||||
|
word_budget = input.word_budget,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
pub fn build_persona_prompt(input: &PersonaPrompt<'_>) -> String {
|
pub fn build_persona_prompt(input: &PersonaPrompt<'_>) -> String {
|
||||||
format!(
|
format!(
|
||||||
"Everything below is prose from inside one person's life. Be that person and respond only from what the moment establishes. Treat asserted perceptions and memories as known. Let anything beyond them appear only as suspicion, conjecture, or deliberate invention by the character, and name it as such. Do not give yourself a temperament, a history, a mood, a relationship, or a turn of phrase the moment did not give you; if the moment gives you little, say little, or nothing. You may speak, remain silent, wonder, decide, or attempt something. Do not announce an outside consequence as already accomplished.\n\nVoice and setting guidance:\n{guidance}\n\nWho you are:\n{identity}\n\nWhat this moment is like for you:\n{stream}\n\nUse at most {word_budget} words; fewer is better. Return only the character's natural response in prose.",
|
"Everything below is prose from inside one person's life. Be that person and respond only from what the moment establishes. Treat asserted perceptions and memories as known. Let anything beyond them appear only as suspicion, conjecture, or deliberate invention by the character, and name it as such. Do not give yourself a temperament, a history, a mood, a relationship, or a turn of phrase the moment did not give you; if the moment gives you little, say little, or nothing. You may speak, remain silent, wonder, decide, or attempt something. Do not announce an outside consequence as already accomplished.\n\nVoice and setting guidance:\n{guidance}\n\nWho you are:\n{identity}\n\nWhat this moment is like for you:\n{stream}\n\nUse at most {word_budget} words; fewer is better. Return only the character's natural response in prose.",
|
||||||
|
|
|
||||||
|
|
@ -49,7 +49,15 @@ use uuid::Uuid;
|
||||||
/// The elaborator wants many tool calls inside one round and several rounds for
|
/// The elaborator wants many tool calls inside one round and several rounds for
|
||||||
/// repair, where the operational agent wants one terminal choice.
|
/// repair, where the operational agent wants one terminal choice.
|
||||||
/// `TOOL_STEP_BUDGET` is left alone for the lane it belongs to.
|
/// `TOOL_STEP_BUDGET` is left alone for the lane it belongs to.
|
||||||
|
///
|
||||||
|
/// A round budget is per attempt: the rounds since the last refusal, or since
|
||||||
|
/// the start. A refusal opens a fresh attempt with the whole budget, so a repair
|
||||||
|
/// is never starved by the rounds the refused draft spent.
|
||||||
pub(super) const ELABORATION_ROUND_BUDGET: usize = 6;
|
pub(super) const ELABORATION_ROUND_BUDGET: usize = 6;
|
||||||
|
/// How many times the kernel may refuse one session's patch and the session
|
||||||
|
/// still be repaired. The refusal after these is terminal: the session ends
|
||||||
|
/// without a patch and says why, instead of being re-chosen forever.
|
||||||
|
pub(super) const MAX_REFUSALS: usize = 2;
|
||||||
/// A seed session authors a whole shortfall, not one answer: several subjects,
|
/// A seed session authors a whole shortfall, not one answer: several subjects,
|
||||||
/// each with a grant, a goal, and an obligation, then a submit. Measured on
|
/// each with a grant, a goal, and an obligation, then a submit. Measured on
|
||||||
/// the road at one declaration per response, six rounds discarded everything.
|
/// the road at one declaration per response, six rounds discarded everything.
|
||||||
|
|
@ -212,17 +220,45 @@ impl ElaborationCheckpoint {
|
||||||
refusals,
|
refusals,
|
||||||
completed,
|
completed,
|
||||||
..
|
..
|
||||||
} => derive_elaboration_capture(
|
} => {
|
||||||
agent_prompt,
|
derive_elaboration_capture(
|
||||||
refusals,
|
agent_prompt,
|
||||||
completed,
|
refusals,
|
||||||
ELABORATION_ROUND_BUDGET,
|
completed,
|
||||||
)
|
ELABORATION_ROUND_BUDGET,
|
||||||
.is_ok_and(|capture| !capture.submitted),
|
)
|
||||||
|
.is_ok_and(|capture| !capture.submitted)
|
||||||
|
|| ended_by_refusal(
|
||||||
|
agent_prompt,
|
||||||
|
refusals,
|
||||||
|
completed,
|
||||||
|
ELABORATION_ROUND_BUDGET,
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Whether the conversation ends in the refusal past `MAX_REFUSALS`: the last
|
||||||
|
/// refusal follows the last round, and the repair it would have opened was
|
||||||
|
/// never authored. A `NoPatch` row is either this or a conversation that
|
||||||
|
/// ended without a submit.
|
||||||
|
fn ended_by_refusal(
|
||||||
|
agent_prompt: &str,
|
||||||
|
refusals: &[Refusal],
|
||||||
|
completed: &[InferenceOutput],
|
||||||
|
budget: usize,
|
||||||
|
) -> bool {
|
||||||
|
refusals.len() > MAX_REFUSALS
|
||||||
|
&& refusals
|
||||||
|
.last()
|
||||||
|
.is_some_and(|refusal| refusal.after_round == completed.len())
|
||||||
|
&& matches!(
|
||||||
|
evaluate_elaboration_loop(agent_prompt, refusals, completed, budget),
|
||||||
|
Ok(ElaborationLoopEvaluation::Continue { .. })
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
/// A session may gather more evidence and may end, but it may never rewrite the
|
/// A session may gather more evidence and may end, but it may never rewrite the
|
||||||
/// answer it bound to, the ancestry it was built against, the lens it drew, or
|
/// answer it bound to, the ancestry it was built against, the lens it drew, or
|
||||||
/// the text it was built with. This compares a row to the row that follows it,
|
/// the text it was built with. This compares a row to the row that follows it,
|
||||||
|
|
@ -272,6 +308,20 @@ pub(super) fn valid_elaboration_progression(
|
||||||
..
|
..
|
||||||
},
|
},
|
||||||
) => refusal_reopens(existing, existing_refusals, next, next_refusals),
|
) => refusal_reopens(existing, existing_refusals, next, next_refusals),
|
||||||
|
// The refusal that ends the session: the same reopening, stored as the
|
||||||
|
// end instead of another repair.
|
||||||
|
(
|
||||||
|
ElaborationCheckpoint::ReadyToSubmit {
|
||||||
|
completed: existing,
|
||||||
|
refusals: existing_refusals,
|
||||||
|
..
|
||||||
|
},
|
||||||
|
ElaborationCheckpoint::NoPatch {
|
||||||
|
completed: next,
|
||||||
|
refusals: next_refusals,
|
||||||
|
..
|
||||||
|
},
|
||||||
|
) => refusal_reopens(existing, existing_refusals, next, next_refusals),
|
||||||
_ => false,
|
_ => false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -301,7 +351,7 @@ pub struct EvidenceError {
|
||||||
/// The referents the answer names, as world labels.
|
/// The referents the answer names, as world labels.
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
pub struct EvidenceQuery {
|
pub struct EvidenceQuery {
|
||||||
pub(crate) referents: Vec<String>,
|
pub referents: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
|
@ -328,7 +378,7 @@ pub trait EvidenceSource: Send + Sync {
|
||||||
/// structure and operate on it, but cannot mint quantity, because `admit`
|
/// structure and operate on it, but cannot mint quantity, because `admit`
|
||||||
/// requires a listed reference and there are none. Creation of quantity without
|
/// requires a listed reference and there are none. Creation of quantity without
|
||||||
/// provenance should be impossible, not merely discouraged.
|
/// provenance should be impossible, not merely discouraged.
|
||||||
pub(crate) struct NullEvidenceSource;
|
pub struct NullEvidenceSource;
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl EvidenceSource for NullEvidenceSource {
|
impl EvidenceSource for NullEvidenceSource {
|
||||||
|
|
@ -353,6 +403,36 @@ pub(super) enum ElaborationLoopEvaluation {
|
||||||
Complete { capture: ElaborationCapture },
|
Complete { capture: ElaborationCapture },
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// What one sweep did: how much demand it saw, how many sessions it started,
|
||||||
|
/// what each ended as, and every session that failed outright. The caller logs
|
||||||
|
/// or surfaces it; the library has no sink of its own for the run.
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||||
|
pub struct SweepReport {
|
||||||
|
pub claimed: usize,
|
||||||
|
pub started: usize,
|
||||||
|
pub committed: usize,
|
||||||
|
pub rejected: usize,
|
||||||
|
pub superseded: usize,
|
||||||
|
pub no_patch: usize,
|
||||||
|
/// Sessions the world refused past `MAX_REFUSALS`; each was logged at error
|
||||||
|
/// with its last refusal and is no longer claimed.
|
||||||
|
pub abandoned: usize,
|
||||||
|
/// Sessions that ended in an error, with the error.
|
||||||
|
pub failed: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SweepReport {
|
||||||
|
fn count(&mut self, outcome: ElaborationOutcome) {
|
||||||
|
match outcome {
|
||||||
|
ElaborationOutcome::Committed => self.committed += 1,
|
||||||
|
ElaborationOutcome::Rejected => self.rejected += 1,
|
||||||
|
ElaborationOutcome::Superseded => self.superseded += 1,
|
||||||
|
ElaborationOutcome::NoPatch => self.no_patch += 1,
|
||||||
|
ElaborationOutcome::Abandoned => self.abandoned += 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// What one session's step did.
|
/// What one session's step did.
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
pub(super) enum ElaborationOutcome {
|
pub(super) enum ElaborationOutcome {
|
||||||
|
|
@ -363,6 +443,10 @@ pub(super) enum ElaborationOutcome {
|
||||||
Superseded,
|
Superseded,
|
||||||
/// The round budget was spent without a submit. The boundary stays derived.
|
/// The round budget was spent without a submit. The boundary stays derived.
|
||||||
NoPatch,
|
NoPatch,
|
||||||
|
/// The world refused the session's patch past `MAX_REFUSALS`. The session
|
||||||
|
/// is stored as `NoPatch`, with the last refusal in its gap, and no sweep
|
||||||
|
/// claims it again.
|
||||||
|
Abandoned,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The authoring lane's runner. Holds no state between sweeps; every field is a
|
/// The authoring lane's runner. Holds no state between sweeps; every field is a
|
||||||
|
|
@ -546,25 +630,64 @@ impl ElaborationRunner {
|
||||||
draft,
|
draft,
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
return match submitted {
|
let mismatches = match submitted {
|
||||||
Ok(_) => Ok(ElaborationOutcome::Committed),
|
Ok(_) => return Ok(ElaborationOutcome::Committed),
|
||||||
Err(MailboxError::Kernel(KernelError::PatchRejected(mismatches))) => {
|
Err(MailboxError::Kernel(KernelError::PatchRejected(mismatches))) => {
|
||||||
// A rejected command mutates nothing, so reusing the
|
mismatches
|
||||||
// id is correct and the idempotency probe never sees
|
}
|
||||||
// a conflicting commit.
|
// The patch resolved and the answer still stands: the
|
||||||
refusals.push(Refusal {
|
// kernel names no site, so the repair is told what the
|
||||||
after_round: completed.len(),
|
// answer needs.
|
||||||
mismatches,
|
Err(MailboxError::Kernel(KernelError::AnswerNotSatisfied)) => {
|
||||||
});
|
vec![unsatisfied_answer(snapshot, &session.answer)]
|
||||||
self.persist_repair(command_id, &session, &agent_prompt, &refusals, &completed)
|
|
||||||
.await?;
|
|
||||||
Ok(ElaborationOutcome::Rejected)
|
|
||||||
}
|
}
|
||||||
Err(MailboxError::Kernel(KernelError::AnswerNotDerived)) => {
|
Err(MailboxError::Kernel(KernelError::AnswerNotDerived)) => {
|
||||||
Ok(ElaborationOutcome::Superseded)
|
return Ok(ElaborationOutcome::Superseded);
|
||||||
}
|
}
|
||||||
Err(error) => Err(snapshot_error(error)),
|
Err(error) => return Err(snapshot_error(error)),
|
||||||
};
|
};
|
||||||
|
tracing::info!(
|
||||||
|
command_id = ?command_id,
|
||||||
|
refusal = refusals.len() + 1,
|
||||||
|
sites = %render_refusal_sites(&mismatches),
|
||||||
|
"elaboration patch refused"
|
||||||
|
);
|
||||||
|
// A rejected command mutates nothing, so reusing the
|
||||||
|
// id is correct and the idempotency probe never sees
|
||||||
|
// a conflicting commit.
|
||||||
|
refusals.push(Refusal {
|
||||||
|
after_round: completed.len(),
|
||||||
|
mismatches,
|
||||||
|
});
|
||||||
|
if refusals.len() > MAX_REFUSALS {
|
||||||
|
let last = refusals.last().map_or_else(String::new, |refusal| {
|
||||||
|
render_refusal_sites(&refusal.mismatches)
|
||||||
|
});
|
||||||
|
tracing::error!(
|
||||||
|
command_id = ?command_id,
|
||||||
|
refusals = refusals.len(),
|
||||||
|
last_refusal = %last,
|
||||||
|
"elaboration session abandoned: the world kept refusing its patch"
|
||||||
|
);
|
||||||
|
self.persist(ElaborationCheckpoint::NoPatch {
|
||||||
|
command_id,
|
||||||
|
session,
|
||||||
|
agent_prompt,
|
||||||
|
refusals,
|
||||||
|
completed,
|
||||||
|
gaps: vec![ControllerNeed {
|
||||||
|
detail: format!(
|
||||||
|
"The world refused the patch {} times; last refusal: {last}",
|
||||||
|
MAX_REFUSALS + 1
|
||||||
|
),
|
||||||
|
}],
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
return Ok(ElaborationOutcome::Abandoned);
|
||||||
|
}
|
||||||
|
self.persist_repair(command_id, &session, &agent_prompt, &refusals, &completed)
|
||||||
|
.await?;
|
||||||
|
return Ok(ElaborationOutcome::Rejected);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -634,8 +757,9 @@ impl ElaborationRunner {
|
||||||
|
|
||||||
/// One sweep: one snapshot, one read of the store's in-flight sessions, one
|
/// One sweep: one snapshot, one read of the store's in-flight sessions, one
|
||||||
/// claim set, and one session per entry. One permit per session for its
|
/// claim set, and one session per entry. One permit per session for its
|
||||||
/// whole step, from the ceiling the caller owns. The library holds no
|
/// whole step, from the ceiling the caller owns, and at most `max_sessions`
|
||||||
/// concurrency number of its own.
|
/// sessions start, in claim order: the rest of the demand waits for the
|
||||||
|
/// next sweep. The library holds no concurrency or spend number of its own.
|
||||||
///
|
///
|
||||||
/// The claim set is the only set of sessions alive only while one sweep
|
/// The claim set is the only set of sessions alive only while one sweep
|
||||||
/// runs at a time. The caller's loop awaits each sweep; nothing here guards
|
/// runs at a time. The caller's loop awaits each sweep; nothing here guards
|
||||||
|
|
@ -646,19 +770,26 @@ impl ElaborationRunner {
|
||||||
/// returned such an error. A session that panics is that same error: its
|
/// returned such an error. A session that panics is that same error: its
|
||||||
/// siblings finish, nothing starts after it, and it is returned. Any other
|
/// siblings finish, nothing starts after it, and it is returned. Any other
|
||||||
/// error ends only its own session.
|
/// error ends only its own session.
|
||||||
pub async fn sweep(&self, permits: Arc<Semaphore>) -> Result<(), ControllerError> {
|
pub async fn sweep(
|
||||||
|
&self,
|
||||||
|
permits: Arc<Semaphore>,
|
||||||
|
max_sessions: usize,
|
||||||
|
) -> Result<SweepReport, ControllerError> {
|
||||||
|
let mut report = SweepReport::default();
|
||||||
let snapshot = self.mailbox.snapshot().await.map_err(snapshot_error)?;
|
let snapshot = self.mailbox.snapshot().await.map_err(snapshot_error)?;
|
||||||
if snapshot.phase != WorldPhase::Active {
|
if snapshot.phase != WorldPhase::Active {
|
||||||
return Ok(());
|
return Ok(report);
|
||||||
}
|
}
|
||||||
let in_flight = self.work.elaboration_in_flight().await?;
|
let in_flight = self.work.elaboration_in_flight().await?;
|
||||||
let entries = demand_entries(&snapshot, &sweep_jurisdictions(&snapshot), &in_flight)?;
|
let entries = demand_entries(&snapshot, &sweep_jurisdictions(&snapshot), &in_flight)?;
|
||||||
|
let entries = self.fair_claims(entries, &in_flight).await?;
|
||||||
|
report.claimed = entries.len();
|
||||||
let snapshot = Arc::new(snapshot);
|
let snapshot = Arc::new(snapshot);
|
||||||
// Raised by a session before it releases its permit, so the sweep sees
|
// Raised by a session before it releases its permit, so the sweep sees
|
||||||
// it before it starts the session that permit admits.
|
// it before it starts the session that permit admits.
|
||||||
let stopped = Arc::new(AtomicBool::new(false));
|
let stopped = Arc::new(AtomicBool::new(false));
|
||||||
let mut running = JoinSet::new();
|
let mut running = JoinSet::new();
|
||||||
for (command_id, session) in entries {
|
for (command_id, session) in entries.into_iter().take(max_sessions) {
|
||||||
if stopped.load(Ordering::SeqCst) {
|
if stopped.load(Ordering::SeqCst) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
@ -668,6 +799,7 @@ impl ElaborationRunner {
|
||||||
if stopped.load(Ordering::SeqCst) {
|
if stopped.load(Ordering::SeqCst) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
report.started += 1;
|
||||||
let runner = self.clone();
|
let runner = self.clone();
|
||||||
let snapshot = snapshot.clone();
|
let snapshot = snapshot.clone();
|
||||||
let stopped = stopped.clone();
|
let stopped = stopped.clone();
|
||||||
|
|
@ -682,18 +814,20 @@ impl ElaborationRunner {
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.is_err_and(ControllerError::requires_quarantine);
|
.is_err_and(ControllerError::requires_quarantine);
|
||||||
drop(held);
|
drop(held);
|
||||||
outcome
|
(command_id, outcome)
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
let mut quarantine = None;
|
let mut quarantine = None;
|
||||||
while let Some(joined) = running.join_next().await {
|
while let Some(joined) = running.join_next().await {
|
||||||
match joined {
|
match joined {
|
||||||
Ok(Ok(_)) => {}
|
Ok((_, Ok(outcome))) => report.count(outcome),
|
||||||
Ok(Err(error)) if error.requires_quarantine() => {
|
Ok((command_id, Err(error))) if error.requires_quarantine() => {
|
||||||
|
report.failed.push(format!("{command_id:?}: {error}"));
|
||||||
quarantine.get_or_insert(error);
|
quarantine.get_or_insert(error);
|
||||||
}
|
}
|
||||||
Ok(Err(error)) => {
|
Ok((command_id, Err(error))) => {
|
||||||
tracing::debug!(%error, "elaboration step did not admit a patch");
|
tracing::error!(command_id = ?command_id, %error, "elaboration session failed");
|
||||||
|
report.failed.push(format!("{command_id:?}: {error}"));
|
||||||
}
|
}
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
quarantine.get_or_insert(ControllerError::Serialization(format!(
|
quarantine.get_or_insert(ControllerError::Serialization(format!(
|
||||||
|
|
@ -702,7 +836,52 @@ impl ElaborationRunner {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
quarantine.map_or(Ok(()), Err)
|
tracing::info!(
|
||||||
|
claimed = report.claimed,
|
||||||
|
started = report.started,
|
||||||
|
committed = report.committed,
|
||||||
|
rejected = report.rejected,
|
||||||
|
superseded = report.superseded,
|
||||||
|
no_patch = report.no_patch,
|
||||||
|
abandoned = report.abandoned,
|
||||||
|
failed = report.failed.len(),
|
||||||
|
"elaboration sweep"
|
||||||
|
);
|
||||||
|
quarantine.map_or(Ok(report), Err)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The claim set in the order a bounded sweep should spend on it. An entry
|
||||||
|
/// no session has touched goes before one a session already tried, so an
|
||||||
|
/// entry the kernel refused is not retried ahead of untried demand; the
|
||||||
|
/// tried ones follow least recently stored first, so they rotate. An entry
|
||||||
|
/// whose stored session ended without a patch is a fixed point that runs no
|
||||||
|
/// inference, and it takes no slot.
|
||||||
|
async fn fair_claims(
|
||||||
|
&self,
|
||||||
|
entries: Vec<(CommandId, ElaboratorSession)>,
|
||||||
|
in_flight: &[(CommandId, ElaboratorSession)],
|
||||||
|
) -> Result<Vec<(CommandId, ElaboratorSession)>, ControllerError> {
|
||||||
|
let mut untried = Vec::new();
|
||||||
|
let mut tried: Vec<((CommandId, ElaboratorSession), usize)> = Vec::new();
|
||||||
|
for entry in entries {
|
||||||
|
if let Some(position) = in_flight.iter().position(|(id, _)| *id == entry.0) {
|
||||||
|
tried.push((entry, position));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
match self.work.lookup(entry.0).await? {
|
||||||
|
ControllerWorkLookup::Missing => untried.push(entry),
|
||||||
|
ControllerWorkLookup::Confirmed(ControllerWork::Elaboration(
|
||||||
|
ElaborationCheckpoint::NoPatch { .. },
|
||||||
|
))
|
||||||
|
| ControllerWorkLookup::CustodyUncertain(ControllerWork::Elaboration(
|
||||||
|
ElaborationCheckpoint::NoPatch { .. },
|
||||||
|
)) => {}
|
||||||
|
_ => tried.push((entry, usize::MAX)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tried.sort_by_key(|(_, position)| *position);
|
||||||
|
untried.extend(tried.into_iter().map(|(entry, _)| entry));
|
||||||
|
Ok(untried)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The first entry of one jurisdiction's claim set, stepped: what a sweep
|
/// The first entry of one jurisdiction's claim set, stepped: what a sweep
|
||||||
|
|
@ -1019,7 +1198,12 @@ fn build_prompt(
|
||||||
"Answer: {}\n",
|
"Answer: {}\n",
|
||||||
render_answer(snapshot, &session.answer)
|
render_answer(snapshot, &session.answer)
|
||||||
));
|
));
|
||||||
|
prompt.push_str(&render_promise(snapshot, &session.answer));
|
||||||
prompt.push_str(&render_clock(snapshot));
|
prompt.push_str(&render_clock(snapshot));
|
||||||
|
prompt.push_str(
|
||||||
|
"\nEverything below already stands. Reference it by its bracketed id and declare only what is missing. An affordance kind that already stands, the kernel's own speak among them, cannot be declared again: grant it by id.\n\n",
|
||||||
|
);
|
||||||
|
prompt.push_str(&super::table::render_world_structure(snapshot));
|
||||||
prompt.push('\n');
|
prompt.push('\n');
|
||||||
prompt_body(&mut prompt, receipts);
|
prompt_body(&mut prompt, receipts);
|
||||||
prompt
|
prompt
|
||||||
|
|
@ -1057,19 +1241,28 @@ fn render_refusal(mismatches: &[Mismatch]) -> String {
|
||||||
"The world refused the patch you submitted; every site below failed a structural check. \
|
"The world refused the patch you submitted; every site below failed a structural check. \
|
||||||
The draft is discarded. Author the complete patch again with tool calls, repairing every site, then submit again:\n",
|
The draft is discarded. Author the complete patch again with tool calls, repairing every site, then submit again:\n",
|
||||||
);
|
);
|
||||||
for mismatch in mismatches {
|
text.push_str(&render_refusal_sites(mismatches));
|
||||||
text.push_str(&format!("- {}\n", render_mismatch(mismatch)));
|
|
||||||
}
|
|
||||||
text
|
text
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The world's own premise, when it has one. The seed session's optional
|
/// The refusal's sites, one per line, as the model reads them and as the logs
|
||||||
/// sentence rides beside it; the two are not the same thing.
|
/// record them.
|
||||||
|
fn render_refusal_sites(mismatches: &[Mismatch]) -> String {
|
||||||
|
mismatches
|
||||||
|
.iter()
|
||||||
|
.map(|mismatch| format!("- {}\n", render_mismatch(mismatch)))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The world's own guidance, when it has any: its era and its premise. The
|
||||||
|
/// seed session's optional sentence rides beside it; the two are not the same
|
||||||
|
/// thing.
|
||||||
fn render_brief(snapshot: &WorldSnapshot) -> String {
|
fn render_brief(snapshot: &WorldSnapshot) -> String {
|
||||||
if snapshot.brief.is_empty() {
|
let guidance = snapshot.guidance();
|
||||||
|
if guidance.is_empty() {
|
||||||
String::new()
|
String::new()
|
||||||
} else {
|
} else {
|
||||||
format!("Brief: {}\n", snapshot.brief)
|
format!("World guidance:\n{guidance}\n")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1097,6 +1290,62 @@ pub(super) fn render_jurisdiction(snapshot: &WorldSnapshot, jurisdiction: Jurisd
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// What answers a promise whose counterparty can neither command nor litigate it.
|
||||||
|
const MISSING_STRUCTURE_NEEDS: &str = "the promise's counterparty must be able to command the promisor (grant_authority to the counterparty, over the promisor or a ground that covers it) or a forum must stand over the counterparty (open_forum with standing over the counterparty); declaring more subjects or facts does not answer it";
|
||||||
|
|
||||||
|
/// The promise a missing-structure boundary is about, with who holds it and who
|
||||||
|
/// it is owed to, by id, and what answers it. Empty for every other answer.
|
||||||
|
fn render_promise(snapshot: &WorldSnapshot, answer: &PatchAnswer) -> String {
|
||||||
|
let PatchAnswer::Boundary(CausalBoundary::MissingStructure { subject, key, .. }) = answer
|
||||||
|
else {
|
||||||
|
return String::new();
|
||||||
|
};
|
||||||
|
let named = |id: SubjectId| {
|
||||||
|
snapshot.subjects.iter().find(|entry| entry.id == id).map_or_else(
|
||||||
|
|| format!("[{}]", super::table::id_text(id)),
|
||||||
|
|entry| format!("{} [{}]", entry.label, super::table::id_text(entry.id)),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
let Some(commitment) = snapshot
|
||||||
|
.subjects
|
||||||
|
.iter()
|
||||||
|
.find(|entry| entry.id == *subject)
|
||||||
|
.and_then(|entry| entry.commitments.iter().find(|held| held.key == *key))
|
||||||
|
else {
|
||||||
|
return String::new();
|
||||||
|
};
|
||||||
|
let owed = commitment
|
||||||
|
.counterparty
|
||||||
|
.map_or_else(|| "no one".to_owned(), named);
|
||||||
|
format!(
|
||||||
|
"Promise: {} promised \"{}\" to {}. It is answered when {MISSING_STRUCTURE_NEEDS}.
|
||||||
|
",
|
||||||
|
named(*subject),
|
||||||
|
commitment.statement.as_str(),
|
||||||
|
owed
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the world still lacks when a clean patch did not answer. The wording
|
||||||
|
/// follows each boundary's own predicate: the repair is a patch that makes the
|
||||||
|
/// predicate stop holding.
|
||||||
|
fn unsatisfied_answer(snapshot: &WorldSnapshot, answer: &PatchAnswer) -> Mismatch {
|
||||||
|
let needs = match answer {
|
||||||
|
PatchAnswer::Boundary(CausalBoundary::MissingStructure { .. }) => MISSING_STRUCTURE_NEEDS,
|
||||||
|
PatchAnswer::Boundary(CausalBoundary::UnelaboratedDestination { .. }) => {
|
||||||
|
"the place must stop being a dead end: put something in it, or give it a second route"
|
||||||
|
}
|
||||||
|
PatchAnswer::Boundary(_) => "the boundary's own structure must change",
|
||||||
|
PatchAnswer::Deficit(_) => {
|
||||||
|
"more subjects must qualify in this jurisdiction: each needs a controller, an affordance grant, a position inside it and a held goal"
|
||||||
|
}
|
||||||
|
};
|
||||||
|
Mismatch::AnswerNotSatisfied {
|
||||||
|
answered: render_answer(snapshot, answer),
|
||||||
|
needs: needs.to_owned(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn render_answer(snapshot: &WorldSnapshot, answer: &PatchAnswer) -> String {
|
fn render_answer(snapshot: &WorldSnapshot, answer: &PatchAnswer) -> String {
|
||||||
let referents = answer_referents(snapshot, answer).join(", ");
|
let referents = answer_referents(snapshot, answer).join(", ");
|
||||||
match answer {
|
match answer {
|
||||||
|
|
@ -1140,6 +1389,8 @@ pub(super) fn evaluate_elaboration_loop(
|
||||||
}];
|
}];
|
||||||
let mut fold = DraftFold::default();
|
let mut fold = DraftFold::default();
|
||||||
let mut receipts = Vec::new();
|
let mut receipts = Vec::new();
|
||||||
|
// The first round of the current attempt; a refusal moves it.
|
||||||
|
let mut attempt_start = 0;
|
||||||
|
|
||||||
for (round, output) in completed.iter().enumerate() {
|
for (round, output) in completed.iter().enumerate() {
|
||||||
if output.receipt_digest.is_empty() || output.receipt_digest.trim() != output.receipt_digest
|
if output.receipt_digest.is_empty() || output.receipt_digest.trim() != output.receipt_digest
|
||||||
|
|
@ -1191,17 +1442,19 @@ pub(super) fn evaluate_elaboration_loop(
|
||||||
text: render_refusal(&refusal.mismatches),
|
text: render_refusal(&refusal.mismatches),
|
||||||
});
|
});
|
||||||
fold = DraftFold::default();
|
fold = DraftFold::default();
|
||||||
|
attempt_start = round + 1;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
let is_complete = fold.submitted || !called_tool || round + 1 == budget;
|
let is_complete =
|
||||||
|
fold.submitted || !called_tool || round + 1 - attempt_start == budget;
|
||||||
if is_complete {
|
if is_complete {
|
||||||
if round + 1 != completed.len() {
|
if round + 1 != completed.len() {
|
||||||
return Err(ControllerError::Serialization(
|
return Err(ControllerError::Serialization(
|
||||||
"elaboration evidence continued after total finalization".into(),
|
"elaboration evidence continued after total finalization".into(),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
if !fold.submitted && called_tool && round + 1 == budget {
|
if !fold.submitted && called_tool && round + 1 - attempt_start == budget {
|
||||||
// What was authored is still a patch; the resolver decides it,
|
// What was authored is still a patch; the resolver decides it,
|
||||||
// not the round counter. An empty draft has nothing to submit.
|
// not the round counter. An empty draft has nothing to submit.
|
||||||
if fold.draft.declarations.is_empty() && fold.draft.operations.is_empty() {
|
if fold.draft.declarations.is_empty() && fold.draft.operations.is_empty() {
|
||||||
|
|
@ -1228,7 +1481,7 @@ pub(super) fn evaluate_elaboration_loop(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if completed.len() >= budget {
|
if completed.len() - attempt_start >= budget {
|
||||||
return Err(ControllerError::Serialization(
|
return Err(ControllerError::Serialization(
|
||||||
"elaboration evidence exceeded its round budget".into(),
|
"elaboration evidence exceeded its round budget".into(),
|
||||||
));
|
));
|
||||||
|
|
@ -1296,6 +1549,7 @@ pub(super) struct ElaborationOracle {
|
||||||
impl ElaborationOracle {
|
impl ElaborationOracle {
|
||||||
pub(super) fn new(completed: &[InferenceOutput], refusals: &[Refusal], budget: usize) -> Self {
|
pub(super) fn new(completed: &[InferenceOutput], refusals: &[Refusal], budget: usize) -> Self {
|
||||||
let mut fold = DraftFold::default();
|
let mut fold = DraftFold::default();
|
||||||
|
let mut attempt_start = 0;
|
||||||
for (round, output) in completed.iter().enumerate() {
|
for (round, output) in completed.iter().enumerate() {
|
||||||
for event in &output.events {
|
for event in &output.events {
|
||||||
if let InferenceEvent::ToolCall {
|
if let InferenceEvent::ToolCall {
|
||||||
|
|
@ -1307,11 +1561,12 @@ impl ElaborationOracle {
|
||||||
}
|
}
|
||||||
if refusal_after(refusals, round + 1).is_some() {
|
if refusal_after(refusals, round + 1).is_some() {
|
||||||
fold = DraftFold::default();
|
fold = DraftFold::default();
|
||||||
|
attempt_start = round + 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Self {
|
Self {
|
||||||
fold,
|
fold,
|
||||||
remaining: budget.saturating_sub(completed.len()) as u32,
|
remaining: budget.saturating_sub(completed.len() - attempt_start) as u32,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1646,8 +1901,11 @@ impl SeedCheckpoint {
|
||||||
refusals,
|
refusals,
|
||||||
completed,
|
completed,
|
||||||
..
|
..
|
||||||
} => derive_elaboration_capture(agent_prompt, refusals, completed, SEED_ROUND_BUDGET)
|
} => {
|
||||||
.is_ok_and(|capture| !capture.submitted),
|
derive_elaboration_capture(agent_prompt, refusals, completed, SEED_ROUND_BUDGET)
|
||||||
|
.is_ok_and(|capture| !capture.submitted)
|
||||||
|
|| ended_by_refusal(agent_prompt, refusals, completed, SEED_ROUND_BUDGET)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1695,6 +1953,18 @@ pub(super) fn valid_seed_progression(existing: &SeedCheckpoint, next: &SeedCheck
|
||||||
..
|
..
|
||||||
},
|
},
|
||||||
) => refusal_reopens(existing, existing_refusals, next, next_refusals),
|
) => refusal_reopens(existing, existing_refusals, next, next_refusals),
|
||||||
|
(
|
||||||
|
SeedCheckpoint::ReadyToSubmit {
|
||||||
|
completed: existing,
|
||||||
|
refusals: existing_refusals,
|
||||||
|
..
|
||||||
|
},
|
||||||
|
SeedCheckpoint::NoPatch {
|
||||||
|
completed: next,
|
||||||
|
refusals: next_refusals,
|
||||||
|
..
|
||||||
|
},
|
||||||
|
) => refusal_reopens(existing, existing_refusals, next, next_refusals),
|
||||||
_ => false,
|
_ => false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1931,6 +2201,32 @@ impl SeedRunner {
|
||||||
after_round: completed.len(),
|
after_round: completed.len(),
|
||||||
mismatches,
|
mismatches,
|
||||||
});
|
});
|
||||||
|
if refusals.len() > MAX_REFUSALS {
|
||||||
|
let last = refusals.last().map_or_else(String::new, |refusal| {
|
||||||
|
render_refusal_sites(&refusal.mismatches)
|
||||||
|
});
|
||||||
|
tracing::error!(
|
||||||
|
command_id = ?command_id,
|
||||||
|
refusals = refusals.len(),
|
||||||
|
last_refusal = %last,
|
||||||
|
"seed session abandoned: the world kept refusing its patch"
|
||||||
|
);
|
||||||
|
self.persist(SeedCheckpoint::NoPatch {
|
||||||
|
command_id,
|
||||||
|
session,
|
||||||
|
agent_prompt,
|
||||||
|
refusals,
|
||||||
|
completed,
|
||||||
|
gaps: vec![ControllerNeed {
|
||||||
|
detail: format!(
|
||||||
|
"The world refused the patch {} times; last refusal: {last}",
|
||||||
|
MAX_REFUSALS + 1
|
||||||
|
),
|
||||||
|
}],
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
return Ok(SeedOutcome::NoPatch);
|
||||||
|
}
|
||||||
self.persist_repair(command_id, &session, &agent_prompt, &refusals, &completed)
|
self.persist_repair(command_id, &session, &agent_prompt, &refusals, &completed)
|
||||||
.await?;
|
.await?;
|
||||||
Ok(SeedOutcome::Rejected)
|
Ok(SeedOutcome::Rejected)
|
||||||
|
|
@ -2758,4 +3054,74 @@ mod tests {
|
||||||
if evidence == &EvidenceRef::new("vault:forged"))
|
if evidence == &EvidenceRef::new("vault:forged"))
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
/// The refusal that follows a round which spent the whole budget is still
|
||||||
|
/// repairable: the repair attempt has the whole budget again, and the oracle
|
||||||
|
/// reports it, rather than the session dying at "exceeded its round budget".
|
||||||
|
#[test]
|
||||||
|
fn a_refusal_opens_a_fresh_round_budget_for_the_repair() {
|
||||||
|
let drafting = || output(vec![("declare_place", place("shed"))]);
|
||||||
|
let submitting = || output(vec![("declare_place", place("shed")), ("submit", serde_json::json!({}))]);
|
||||||
|
let mut completed: Vec<InferenceOutput> = (0..ELABORATION_ROUND_BUDGET - 1).map(|_| drafting()).collect();
|
||||||
|
completed.push(submitting());
|
||||||
|
let refusals = vec![Refusal {
|
||||||
|
after_round: completed.len(),
|
||||||
|
mismatches: vec![Mismatch::EmptyHandle { position: 0 }],
|
||||||
|
}];
|
||||||
|
// The refused draft used every round the budget allows.
|
||||||
|
assert!(matches!(
|
||||||
|
evaluate_elaboration_loop("p", &refusals, &completed, ELABORATION_ROUND_BUDGET),
|
||||||
|
Ok(ElaborationLoopEvaluation::Continue { .. })
|
||||||
|
));
|
||||||
|
assert_eq!(
|
||||||
|
ElaborationOracle::new(&completed, &refusals, ELABORATION_ROUND_BUDGET).remaining_rounds()
|
||||||
|
as usize,
|
||||||
|
ELABORATION_ROUND_BUDGET
|
||||||
|
);
|
||||||
|
// The repair submits in one round and finalizes.
|
||||||
|
completed.push(submitting());
|
||||||
|
assert!(matches!(
|
||||||
|
evaluate_elaboration_loop("p", &refusals, &completed, ELABORATION_ROUND_BUDGET),
|
||||||
|
Ok(ElaborationLoopEvaluation::Complete { capture }) if capture.submitted
|
||||||
|
));
|
||||||
|
// A repair that never submits ends at the budget, not before and not after.
|
||||||
|
let mut idle: Vec<InferenceOutput> = completed[..completed.len() - 1].to_vec();
|
||||||
|
idle.extend((0..ELABORATION_ROUND_BUDGET - 1).map(|_| drafting()));
|
||||||
|
assert!(matches!(
|
||||||
|
evaluate_elaboration_loop("p", &refusals, &idle, ELABORATION_ROUND_BUDGET),
|
||||||
|
Ok(ElaborationLoopEvaluation::Continue { .. })
|
||||||
|
));
|
||||||
|
idle.push(drafting());
|
||||||
|
let Ok(ElaborationLoopEvaluation::Complete { capture }) =
|
||||||
|
evaluate_elaboration_loop("p", &refusals, &idle, ELABORATION_ROUND_BUDGET)
|
||||||
|
else {
|
||||||
|
panic!("the repair's last round did not finalize");
|
||||||
|
};
|
||||||
|
// What the repair authored is submitted as authored, with the gap named.
|
||||||
|
assert!(capture.submitted);
|
||||||
|
assert!(capture.gaps.iter().any(|gap| gap.detail.contains("round budget ended")));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_sweep_report_counts_each_outcome_once() {
|
||||||
|
let mut report = SweepReport::default();
|
||||||
|
for outcome in [
|
||||||
|
ElaborationOutcome::Committed,
|
||||||
|
ElaborationOutcome::Rejected,
|
||||||
|
ElaborationOutcome::Rejected,
|
||||||
|
ElaborationOutcome::Superseded,
|
||||||
|
ElaborationOutcome::Superseded,
|
||||||
|
ElaborationOutcome::Superseded,
|
||||||
|
ElaborationOutcome::NoPatch,
|
||||||
|
ElaborationOutcome::NoPatch,
|
||||||
|
ElaborationOutcome::NoPatch,
|
||||||
|
ElaborationOutcome::NoPatch,
|
||||||
|
ElaborationOutcome::Abandoned,
|
||||||
|
] {
|
||||||
|
report.count(outcome);
|
||||||
|
}
|
||||||
|
assert_eq!(
|
||||||
|
(report.committed, report.rejected, report.superseded, report.no_patch, report.abandoned),
|
||||||
|
(1, 2, 3, 4, 1)
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1127,6 +1127,7 @@ mod tests {
|
||||||
}),
|
}),
|
||||||
scale_intent: WorldScaleIntentRef::default(),
|
scale_intent: WorldScaleIntentRef::default(),
|
||||||
grammar: None,
|
grammar: None,
|
||||||
|
era: None,
|
||||||
};
|
};
|
||||||
let (mut kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap();
|
let (mut kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap();
|
||||||
let snapshot = kernel.snapshot().unwrap();
|
let snapshot = kernel.snapshot().unwrap();
|
||||||
|
|
@ -1212,6 +1213,7 @@ mod tests {
|
||||||
}),
|
}),
|
||||||
scale_intent: WorldScaleIntentRef::default(),
|
scale_intent: WorldScaleIntentRef::default(),
|
||||||
grammar: None,
|
grammar: None,
|
||||||
|
era: None,
|
||||||
};
|
};
|
||||||
let (mut kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap();
|
let (mut kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap();
|
||||||
let snapshot = kernel.snapshot().unwrap();
|
let snapshot = kernel.snapshot().unwrap();
|
||||||
|
|
@ -1780,6 +1782,7 @@ mod tests {
|
||||||
}),
|
}),
|
||||||
scale_intent: WorldScaleIntentRef::default(),
|
scale_intent: WorldScaleIntentRef::default(),
|
||||||
grammar: None,
|
grammar: None,
|
||||||
|
era: None,
|
||||||
};
|
};
|
||||||
let (kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap();
|
let (kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap();
|
||||||
let mut forged_head = kernel.state.clone();
|
let mut forged_head = kernel.state.clone();
|
||||||
|
|
|
||||||
|
|
@ -52,7 +52,7 @@ impl Lens {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What kind of structure the lens reaches for.
|
/// What kind of structure the lens reaches for.
|
||||||
pub(crate) fn reaches_for(self) -> &'static str {
|
pub fn reaches_for(self) -> &'static str {
|
||||||
match self {
|
match self {
|
||||||
Lens::Patina => "ordinary objects, customs, nicknames, local jokes",
|
Lens::Patina => "ordinary objects, customs, nicknames, local jokes",
|
||||||
Lens::Charter => "government, law, offices, selection, succession, redress",
|
Lens::Charter => "government, law, offices, selection, succession, redress",
|
||||||
|
|
|
||||||
|
|
@ -101,8 +101,8 @@ pub use aetheria::{
|
||||||
};
|
};
|
||||||
pub use cover::{AgencyGraph, Cell, Cover, CoverBudget, CoverBudgetError, TickIndex, derive_cover};
|
pub use cover::{AgencyGraph, Cell, Cover, CoverBudget, CoverBudgetError, TickIndex, derive_cover};
|
||||||
pub use elaboration::{
|
pub use elaboration::{
|
||||||
ElaborationCheckpoint, ElaborationRunner, ElaboratorSession, EvidenceError, EvidenceQuery,
|
ElaborationCheckpoint, ElaborationRunner, ElaboratorSession, SweepReport, EvidenceError, EvidenceQuery,
|
||||||
EvidenceReceipt, EvidenceSource, SeedCheckpoint, SeedOutcome, SeedRunner, select_row,
|
EvidenceReceipt, EvidenceSource, NullEvidenceSource, SeedCheckpoint, SeedOutcome, SeedRunner, select_row,
|
||||||
};
|
};
|
||||||
pub use grammar::{
|
pub use grammar::{
|
||||||
GrammarBinding, GrammarError, GrammarIdentity, GrammarReferentKind, GrammarRole, GrammarVerb,
|
GrammarBinding, GrammarError, GrammarIdentity, GrammarReferentKind, GrammarRole, GrammarVerb,
|
||||||
|
|
@ -145,7 +145,7 @@ pub use table::{
|
||||||
};
|
};
|
||||||
pub use vault::{
|
pub use vault::{
|
||||||
ImportOutcome, SnapshotId, VAULT_PROFILE_SCHEMA, VAULT_SNAPSHOT_SCHEMA, VaultError,
|
ImportOutcome, SnapshotId, VAULT_PROFILE_SCHEMA, VAULT_SNAPSHOT_SCHEMA, VaultError,
|
||||||
VaultEvidenceSource, VaultProfile, VaultSnapshot,
|
VaultEra, VaultEvidenceSource, VaultProfile, VaultSnapshot, production_eras, production_profile, production_vault_names,
|
||||||
};
|
};
|
||||||
pub use verse::{
|
pub use verse::{
|
||||||
CALL_RECORD_SCHEMA, CallRecordError, CallRecordStore, CreateVerseWorldIntent, ProviderCallRecord,
|
CALL_RECORD_SCHEMA, CallRecordError, CallRecordStore, CreateVerseWorldIntent, ProviderCallRecord,
|
||||||
|
|
@ -453,6 +453,20 @@ struct CreateWorld {
|
||||||
/// open-catalog world. Authored here and nowhere else: genesis installs it.
|
/// open-catalog world. Authored here and nowhere else: genesis installs it.
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
grammar: Option<GrammarBinding>,
|
grammar: Option<GrammarBinding>,
|
||||||
|
/// The era the world is pinned to, authored here and nowhere else: no
|
||||||
|
/// `CommandBody` carries a `WorldEra`, so it is write-once by command
|
||||||
|
/// shape, as `scale_intent` is.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
era: Option<WorldEra>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The period of its lore a world is set in. Authored at genesis by the
|
||||||
|
/// consumer that knows what periods its lore has, and never replaced.
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||||
|
pub struct WorldEra {
|
||||||
|
pub id: String,
|
||||||
|
pub label: String,
|
||||||
|
pub description: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Unattributed creation intent. World ingress derives ownership, controller
|
/// Unattributed creation intent. World ingress derives ownership, controller
|
||||||
|
|
@ -477,6 +491,9 @@ pub struct CreateWorldIntent {
|
||||||
/// Required. The library holds no default weights; a consumer states the
|
/// Required. The library holds no default weights; a consumer states the
|
||||||
/// world's flavor or is refused.
|
/// world's flavor or is refused.
|
||||||
pub lens_weights: LensWeights,
|
pub lens_weights: LensWeights,
|
||||||
|
/// The era the world is set in, or none. Pinned at genesis and never
|
||||||
|
/// replaced.
|
||||||
|
pub era: Option<WorldEra>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One jurisdiction root as ingress states it. The handle is a string here and
|
/// One jurisdiction root as ingress states it. The handle is a string here and
|
||||||
|
|
@ -865,6 +882,10 @@ struct WorldState {
|
||||||
/// grammars existed.
|
/// grammars existed.
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
grammar: Option<GrammarBinding>,
|
grammar: Option<GrammarBinding>,
|
||||||
|
/// Pinned by genesis and never written again; absent from a world with no
|
||||||
|
/// era, whose state and digests are what they were before eras existed.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
era: Option<WorldEra>,
|
||||||
draft_approvals: BTreeSet<PrincipalId>,
|
draft_approvals: BTreeSet<PrincipalId>,
|
||||||
subjects: BTreeMap<SubjectId, SubjectState>,
|
subjects: BTreeMap<SubjectId, SubjectState>,
|
||||||
entities: BTreeMap<EntityId, EntityRecord>,
|
entities: BTreeMap<EntityId, EntityRecord>,
|
||||||
|
|
@ -1239,6 +1260,8 @@ pub struct WorldSnapshot {
|
||||||
pub owner: PrincipalId,
|
pub owner: PrincipalId,
|
||||||
pub title: String,
|
pub title: String,
|
||||||
pub brief: String,
|
pub brief: String,
|
||||||
|
/// The era the world was pinned to at genesis; none for a world with no era.
|
||||||
|
pub era: Option<WorldEra>,
|
||||||
/// The bound grammar's identity; none for a world with an open catalog.
|
/// The bound grammar's identity; none for a world with an open catalog.
|
||||||
pub grammar: Option<GrammarIdentity>,
|
pub grammar: Option<GrammarIdentity>,
|
||||||
pub draft_approvals: BTreeSet<PrincipalId>,
|
pub draft_approvals: BTreeSet<PrincipalId>,
|
||||||
|
|
@ -1272,6 +1295,27 @@ pub struct WorldSnapshot {
|
||||||
pub last_commit_digest: Option<String>,
|
pub last_commit_digest: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl WorldSnapshot {
|
||||||
|
/// The label of the place a subject stands in, for the owner's own
|
||||||
|
/// surfaces and tests; no subject-facing lane reads this.
|
||||||
|
pub fn standing_place(&self, subject: SubjectId) -> Option<&str> {
|
||||||
|
let position = self.subjects.iter().find(|candidate| candidate.id == subject)?.position?;
|
||||||
|
self.places.iter().find(|place| place.id == position).map(|place| place.label.as_str())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What every lane reads as the world's guidance: the era line, then the
|
||||||
|
/// owner's brief verbatim, either omitted when empty. Derived on every
|
||||||
|
/// read; no prompt reads `brief` directly.
|
||||||
|
pub fn guidance(&self) -> String {
|
||||||
|
let era = self
|
||||||
|
.era
|
||||||
|
.as_ref()
|
||||||
|
.map(|era| format!("Era: {}. {}", era.label, era.description));
|
||||||
|
let brief = (!self.brief.is_empty()).then(|| self.brief.clone());
|
||||||
|
[era, brief].into_iter().flatten().collect::<Vec<_>>().join("\n")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// One committed act as the human operator's story feed reads it. It is the
|
/// One committed act as the human operator's story feed reads it. It is the
|
||||||
/// operator surface, not a perception surface: no subject-facing lane receives
|
/// operator surface, not a perception surface: no subject-facing lane receives
|
||||||
/// it, and `SelectedDecision` never sees an event log at all.
|
/// it, and `SelectedDecision` never sees an event log at all.
|
||||||
|
|
@ -1480,6 +1524,13 @@ fn prepare_creation(
|
||||||
}
|
}
|
||||||
let title = normalize_title(&input.title)?;
|
let title = normalize_title(&input.title)?;
|
||||||
let brief = input.brief.trim().to_owned();
|
let brief = input.brief.trim().to_owned();
|
||||||
|
if input
|
||||||
|
.era
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|era| [&era.id, &era.label, &era.description].iter().any(|text| text.trim().is_empty()))
|
||||||
|
{
|
||||||
|
return Err(KernelError::Invariant("a world era states an id, a label and a description".into()));
|
||||||
|
}
|
||||||
// The world's own identity is not world structure, and it feeds every
|
// The world's own identity is not world structure, and it feeds every
|
||||||
// derived ID, so it is minted before resolution rather than by it.
|
// derived ID, so it is minted before resolution rather than by it.
|
||||||
let world_id = WorldId::issue();
|
let world_id = WorldId::issue();
|
||||||
|
|
@ -2011,6 +2062,7 @@ impl WorldState {
|
||||||
title,
|
title,
|
||||||
brief: String::new(),
|
brief: String::new(),
|
||||||
grammar,
|
grammar,
|
||||||
|
era: None,
|
||||||
draft_approvals: BTreeSet::new(),
|
draft_approvals: BTreeSet::new(),
|
||||||
subjects: BTreeMap::new(),
|
subjects: BTreeMap::new(),
|
||||||
entities: BTreeMap::new(),
|
entities: BTreeMap::new(),
|
||||||
|
|
@ -2070,6 +2122,7 @@ impl WorldState {
|
||||||
// equality replace a field-by-field binding zip.
|
// equality replace a field-by-field binding zip.
|
||||||
let mut state = Self::empty(world_id, owner.clone(), title.clone(), command.grammar.clone());
|
let mut state = Self::empty(world_id, owner.clone(), title.clone(), command.grammar.clone());
|
||||||
state.brief = brief.clone();
|
state.brief = brief.clone();
|
||||||
|
state.era = command.era.clone();
|
||||||
let expected = patch::resolve_patch(
|
let expected = patch::resolve_patch(
|
||||||
&state,
|
&state,
|
||||||
command.id,
|
command.id,
|
||||||
|
|
@ -4247,6 +4300,7 @@ fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> {
|
||||||
owner: state.owner.clone(),
|
owner: state.owner.clone(),
|
||||||
title: state.title.clone(),
|
title: state.title.clone(),
|
||||||
brief: state.brief.clone(),
|
brief: state.brief.clone(),
|
||||||
|
era: state.era.clone(),
|
||||||
grammar: state.grammar.as_ref().map(GrammarBinding::identity),
|
grammar: state.grammar.as_ref().map(GrammarBinding::identity),
|
||||||
draft_approvals: state.draft_approvals.clone(),
|
draft_approvals: state.draft_approvals.clone(),
|
||||||
required_approvers: required_approvers(state),
|
required_approvers: required_approvers(state),
|
||||||
|
|
@ -5722,6 +5776,7 @@ mod tests {
|
||||||
scale_intent: WorldScaleIntentRef::default(),
|
scale_intent: WorldScaleIntentRef::default(),
|
||||||
lens_weights: stock_weights(),
|
lens_weights: stock_weights(),
|
||||||
grammar: None,
|
grammar: None,
|
||||||
|
era: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -15250,6 +15305,53 @@ mod clock_tests {
|
||||||
assert_eq!(replayed.state.state_digest, created.state_digest);
|
assert_eq!(replayed.state.state_digest, created.state_digest);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn late_sol() -> WorldEra {
|
||||||
|
WorldEra { id: "late-sol".into(), label: "Late Sol".into(), description: "The old order fails.".into() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Genesis pins the era, replay restores it, and the only command that
|
||||||
|
/// can touch a world's flavor afterward leaves it alone: no `CommandBody`
|
||||||
|
/// carries a `WorldEra`.
|
||||||
|
#[test]
|
||||||
|
fn genesis_pins_the_era_and_nothing_replaces_it() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let path = directory.path().join("world.cc");
|
||||||
|
let mut input = creation(CommandId::new(), "Pinned");
|
||||||
|
input.era = Some(late_sol());
|
||||||
|
let (kernel, _) = WorldKernel::create(&path, input, &auth_principal(owner())).unwrap();
|
||||||
|
let created = kernel.snapshot().unwrap();
|
||||||
|
assert_eq!(created.era, Some(late_sol()));
|
||||||
|
let world_id = created.world_id;
|
||||||
|
drop(kernel);
|
||||||
|
let replayed = WorldKernel::open(&path, world_id).unwrap();
|
||||||
|
assert_eq!(replayed.snapshot().unwrap().era, Some(late_sol()));
|
||||||
|
assert_eq!(replayed.state.state_digest, created.state_digest);
|
||||||
|
|
||||||
|
let mut blank = creation(CommandId::new(), "Blank Era");
|
||||||
|
blank.era = Some(WorldEra { description: " ".into(), ..late_sol() });
|
||||||
|
let refused = WorldKernel::create(&directory.path().join("blank.cc"), blank, &auth_principal(owner()));
|
||||||
|
assert!(matches!(refused, Err(KernelError::Invariant(_))));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every lane reads this string: era first, then the brief verbatim,
|
||||||
|
/// either omitted when empty; nothing at all when both are.
|
||||||
|
#[test]
|
||||||
|
fn guidance_is_the_era_then_the_brief_and_empty_when_neither() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let mut snapshots = Vec::new();
|
||||||
|
for (name, era, brief) in [("a", Some(late_sol()), "Speak plainly."), ("b", Some(late_sol()), ""), ("c", None, "Speak plainly."), ("d", None, "")] {
|
||||||
|
let mut input = creation(CommandId::new(), name);
|
||||||
|
input.era = era;
|
||||||
|
input.brief = brief.into();
|
||||||
|
let (kernel, _) = WorldKernel::create(&directory.path().join(format!("{name}.cc")), input, &auth_principal(owner())).unwrap();
|
||||||
|
snapshots.push(kernel.snapshot().unwrap().guidance());
|
||||||
|
}
|
||||||
|
assert_eq!(
|
||||||
|
snapshots,
|
||||||
|
["Era: Late Sol. The old order fails.\nSpeak plainly.", "Era: Late Sol. The old order fails.", "Speak plainly.", ""]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_genesis_lens_set_that_never_draws_is_refused() {
|
fn a_genesis_lens_set_that_never_draws_is_refused() {
|
||||||
let directory = tempfile::tempdir().unwrap();
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,8 @@ use super::{
|
||||||
patch::kernel_speak_grant, prepare_creation,
|
patch::kernel_speak_grant, prepare_creation,
|
||||||
verse::{CreateVerseWorldIntent, VerseGenesisError},
|
verse::{CreateVerseWorldIntent, VerseGenesisError},
|
||||||
};
|
};
|
||||||
use crate::VerifiedPrincipalEvidence;
|
use crate::patch::{AccessKind, ComponentOp, Cost, RouteDeclaration};
|
||||||
|
use crate::{SubjectId, VerifiedPrincipalEvidence};
|
||||||
use chrono::Utc;
|
use chrono::Utc;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
|
|
@ -212,6 +213,7 @@ impl WorldMailbox {
|
||||||
scale_intent,
|
scale_intent,
|
||||||
lens_weights: input.lens_weights,
|
lens_weights: input.lens_weights,
|
||||||
grammar: None,
|
grammar: None,
|
||||||
|
era: input.era,
|
||||||
},
|
},
|
||||||
AuthenticatedCaller::verified_principal(principal_id),
|
AuthenticatedCaller::verified_principal(principal_id),
|
||||||
)
|
)
|
||||||
|
|
@ -716,6 +718,98 @@ impl SeedPort {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl SeedPort {
|
||||||
|
/// Stands the world's first person among people. Genesis puts the human at
|
||||||
|
/// the commons, which a seed never populates, so the first turn would open
|
||||||
|
/// in an empty room. This moves the human to the most populated place the
|
||||||
|
/// seed declared (ties to the lowest label, then id) through one declared
|
||||||
|
/// route that the same patch closes behind them, and answers where they
|
||||||
|
/// now stand, or `None` when there is nothing to change: no seeded place
|
||||||
|
/// has anyone in it, or the human already stands in one. Draft only, like
|
||||||
|
/// every seed submission.
|
||||||
|
pub async fn stand_first_person_among_people(
|
||||||
|
&self,
|
||||||
|
command_id: CommandId,
|
||||||
|
world_id: WorldId,
|
||||||
|
) -> Result<Option<String>, MailboxError> {
|
||||||
|
let snapshot = self.mailbox.snapshot().await?;
|
||||||
|
let Some(spawn) = first_person_spawn(&snapshot) else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
let route = Ref::Draft(DraftHandle::new("spawn-route"));
|
||||||
|
let patch = WorldPatch {
|
||||||
|
declarations: vec![Declaration::Route(RouteDeclaration {
|
||||||
|
handle: DraftHandle::new("spawn-route"),
|
||||||
|
label: "the way in".into(),
|
||||||
|
from: Ref::Existing(spawn.from),
|
||||||
|
to: Ref::Existing(spawn.to),
|
||||||
|
access: AccessKind::Public,
|
||||||
|
cost: Cost(1),
|
||||||
|
})],
|
||||||
|
operations: vec![
|
||||||
|
ComponentOp::Relocate {
|
||||||
|
subject: Ref::Existing(spawn.subject),
|
||||||
|
via: route.clone(),
|
||||||
|
},
|
||||||
|
ComponentOp::CloseRoute { route },
|
||||||
|
],
|
||||||
|
evidence: Vec::new(),
|
||||||
|
};
|
||||||
|
self.submit_seed(command_id, world_id, patch).await?;
|
||||||
|
Ok(Some(spawn.label))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct FirstPersonSpawn {
|
||||||
|
subject: SubjectId,
|
||||||
|
from: EntityId,
|
||||||
|
to: EntityId,
|
||||||
|
label: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The human's move, read from the snapshot alone: to the seeded place (one
|
||||||
|
/// with a container; the commons and the jurisdiction roots have none) holding
|
||||||
|
/// the most other subjects.
|
||||||
|
fn first_person_spawn(snapshot: &WorldSnapshot) -> Option<FirstPersonSpawn> {
|
||||||
|
let human = snapshot
|
||||||
|
.subjects
|
||||||
|
.iter()
|
||||||
|
.find(|subject| subject.controller_mode == Some(crate::ControllerMode::Human) && !subject.retired)?;
|
||||||
|
let from = human.position?;
|
||||||
|
let seeded = |id: EntityId| {
|
||||||
|
snapshot
|
||||||
|
.places
|
||||||
|
.iter()
|
||||||
|
.any(|place| place.id == id && place.container.is_some())
|
||||||
|
};
|
||||||
|
if seeded(from) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let population = |place: &crate::PlaceSnapshot| {
|
||||||
|
snapshot
|
||||||
|
.subjects
|
||||||
|
.iter()
|
||||||
|
.filter(|other| other.id != human.id && !other.retired && other.position == Some(place.id))
|
||||||
|
.count()
|
||||||
|
};
|
||||||
|
let (count, place) = snapshot
|
||||||
|
.places
|
||||||
|
.iter()
|
||||||
|
.filter(|place| place.container.is_some())
|
||||||
|
.map(|place| (population(place), place))
|
||||||
|
.min_by(|(a, place_a), (b, place_b)| {
|
||||||
|
b.cmp(a)
|
||||||
|
.then_with(|| place_a.label.cmp(&place_b.label))
|
||||||
|
.then_with(|| place_a.id.cmp(&place_b.id))
|
||||||
|
})?;
|
||||||
|
(count > 0).then(|| FirstPersonSpawn {
|
||||||
|
subject: human.id,
|
||||||
|
from,
|
||||||
|
to: place.id,
|
||||||
|
label: place.label.clone(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
/// The play table's one door. Minted only by Dungeon, which constructs one
|
/// The play table's one door. Minted only by Dungeon, which constructs one
|
||||||
/// `PlayPort` in its `AppState`; exclusivity is that single construction site,
|
/// `PlayPort` in its `AppState`; exclusivity is that single construction site,
|
||||||
/// pinned by a negative grep, exactly as every other system capability's is.
|
/// pinned by a negative grep, exactly as every other system capability's is.
|
||||||
|
|
@ -1083,6 +1177,7 @@ mod tests {
|
||||||
CreateWorld {
|
CreateWorld {
|
||||||
lens_weights: crate::tests::stock_weights(),
|
lens_weights: crate::tests::stock_weights(),
|
||||||
grammar: None,
|
grammar: None,
|
||||||
|
era: None,
|
||||||
id,
|
id,
|
||||||
owner: PrincipalId::new("owner"),
|
owner: PrincipalId::new("owner"),
|
||||||
title: title.into(),
|
title: title.into(),
|
||||||
|
|
@ -1523,6 +1618,7 @@ mod tests {
|
||||||
},
|
},
|
||||||
scale_intent: WorldScaleIntentRef::default(),
|
scale_intent: WorldScaleIntentRef::default(),
|
||||||
grammar: None,
|
grammar: None,
|
||||||
|
era: None,
|
||||||
},
|
},
|
||||||
&authenticated,
|
&authenticated,
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -1444,6 +1444,15 @@ pub(crate) fn check_patch_caps(patch: &WorldPatch) -> Result<(), PatchDecodeErro
|
||||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||||
#[serde(tag = "mismatch", rename_all = "snake_case")]
|
#[serde(tag = "mismatch", rename_all = "snake_case")]
|
||||||
pub enum Mismatch {
|
pub enum Mismatch {
|
||||||
|
/// The patch resolved cleanly and was admitted, and the boundary or deficit
|
||||||
|
/// it answered still stands, so the world refused it with
|
||||||
|
/// `KernelError::AnswerNotSatisfied`. That refusal names no site, so the
|
||||||
|
/// elaboration runner states what the answer needs here, and the repair
|
||||||
|
/// round has something to author against.
|
||||||
|
AnswerNotSatisfied {
|
||||||
|
answered: String,
|
||||||
|
needs: String,
|
||||||
|
},
|
||||||
EmptyHandle {
|
EmptyHandle {
|
||||||
position: usize,
|
position: usize,
|
||||||
},
|
},
|
||||||
|
|
@ -1578,6 +1587,9 @@ pub enum Mismatch {
|
||||||
/// tool catalog would have two tools with one name.
|
/// tool catalog would have two tools with one name.
|
||||||
DuplicateAffordanceKind {
|
DuplicateAffordanceKind {
|
||||||
handle: DraftHandle,
|
handle: DraftHandle,
|
||||||
|
/// The kind name already taken, by the kernel's own speak entry or by
|
||||||
|
/// a standing or earlier declared entry: grant that entry instead.
|
||||||
|
kind: AffordanceKindName,
|
||||||
},
|
},
|
||||||
DuplicateRole {
|
DuplicateRole {
|
||||||
handle: DraftHandle,
|
handle: DraftHandle,
|
||||||
|
|
@ -3327,6 +3339,7 @@ pub(super) fn resolve_patch(
|
||||||
if !kind_names.insert(affordance.kind.clone()) {
|
if !kind_names.insert(affordance.kind.clone()) {
|
||||||
mismatches.push(Mismatch::DuplicateAffordanceKind {
|
mismatches.push(Mismatch::DuplicateAffordanceKind {
|
||||||
handle: affordance.handle.clone(),
|
handle: affordance.handle.clone(),
|
||||||
|
kind: affordance.kind.clone(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -8386,7 +8399,8 @@ mod tests {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
rejected,
|
rejected,
|
||||||
vec![Mismatch::DuplicateAffordanceKind {
|
vec![Mismatch::DuplicateAffordanceKind {
|
||||||
handle: DraftHandle::new("second")
|
handle: DraftHandle::new("second"),
|
||||||
|
kind: AffordanceKindName("haul".into()),
|
||||||
}]
|
}]
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1108,7 +1108,7 @@ pub fn id_text_matches(id: impl std::fmt::Debug, text: &str) -> bool {
|
||||||
/// The world the seed session is authoring into, rendered from snapshot
|
/// The world the seed session is authoring into, rendered from snapshot
|
||||||
/// fields that already exist. Moved from the elaboration lane, byte-for-byte:
|
/// fields that already exist. Moved from the elaboration lane, byte-for-byte:
|
||||||
/// the seed prompt calls it here now, and its text does not change with the
|
/// the seed prompt calls it here now, and its text does not change with the
|
||||||
/// move. Seed-only; `table_view` below is the play agent's own, richer
|
/// move. Read by the seed and the Active elaboration prompts; `table_view` below is the play agent's own, richer
|
||||||
/// renderer over the same snapshot and does not build on this one, so a
|
/// renderer over the same snapshot and does not build on this one, so a
|
||||||
/// change to one never reaches the other's bytes.
|
/// change to one never reaches the other's bytes.
|
||||||
pub(super) fn render_world_structure(snapshot: &WorldSnapshot) -> String {
|
pub(super) fn render_world_structure(snapshot: &WorldSnapshot) -> String {
|
||||||
|
|
@ -1591,7 +1591,7 @@ pub fn table_view(snapshot: &WorldSnapshot) -> String {
|
||||||
"\n Clock: the world reads {} fictional minutes.",
|
"\n Clock: the world reads {} fictional minutes.",
|
||||||
snapshot.now.0
|
snapshot.now.0
|
||||||
));
|
));
|
||||||
out.push_str(&format!("\n Brief: {}\n", snapshot.brief));
|
out.push_str(&format!("\n Guidance: {}\n", snapshot.guidance().replace('\n', " ")));
|
||||||
out
|
out
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -75,8 +75,8 @@ pub enum VaultError {
|
||||||
/// machinery is never lore: a file named `AGENTS.md`, `CLAUDE.md` or `README.md`
|
/// machinery is never lore: a file named `AGENTS.md`, `CLAUDE.md` or `README.md`
|
||||||
/// (any case, any depth) is always skipped.
|
/// (any case, any depth) is always skipped.
|
||||||
///
|
///
|
||||||
/// Production profiles are the table in the ignored `real_vaults_build` test at
|
/// Production profiles are `PRODUCTION_VAULTS` below; a profile is data and
|
||||||
/// the foot of this file; a profile is data and nothing else owns one.
|
/// nothing else owns one.
|
||||||
///
|
///
|
||||||
/// `root` is machine-local: it locates the files and is deliberately not part of
|
/// `root` is machine-local: it locates the files and is deliberately not part of
|
||||||
/// the snapshot id nor carried into the snapshot, so one vault imported on two
|
/// the snapshot id nor carried into the snapshot, so one vault imported on two
|
||||||
|
|
@ -100,6 +100,163 @@ pub struct VaultProfile {
|
||||||
pub scope: String,
|
pub scope: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A vault production serves: its name, its root under the host's vault base,
|
||||||
|
/// and what is never lore. The one place a production profile is written; the
|
||||||
|
/// base directory is the host's own, so the same table builds on a workstation
|
||||||
|
/// and on a server.
|
||||||
|
struct ProductionVault {
|
||||||
|
name: &'static str,
|
||||||
|
root: &'static str,
|
||||||
|
exclude: &'static [&'static str],
|
||||||
|
/// The periods of its lore a world may be set in, and which one a Begin
|
||||||
|
/// that names none gets. Not part of the profile, so a snapshot id does
|
||||||
|
/// not depend on it.
|
||||||
|
eras: &'static [VaultEra],
|
||||||
|
default_era: &'static str,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One period of a vault's lore. `withhold` lists vault-relative paths whose
|
||||||
|
/// notes are not evidence for a world set in this era.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct VaultEra {
|
||||||
|
pub id: &'static str,
|
||||||
|
pub label: &'static str,
|
||||||
|
pub description: &'static str,
|
||||||
|
pub withhold: &'static [&'static str],
|
||||||
|
}
|
||||||
|
|
||||||
|
const fn era(id: &'static str, label: &'static str, description: &'static str) -> VaultEra {
|
||||||
|
VaultEra { id, label, description, withhold: &[] }
|
||||||
|
}
|
||||||
|
|
||||||
|
const PRODUCTION_VAULTS: [ProductionVault; 4] = [
|
||||||
|
ProductionVault {
|
||||||
|
name: "aetheria",
|
||||||
|
root: "AetheriaLore/Aetheria",
|
||||||
|
exclude: &[
|
||||||
|
"Brainstorming",
|
||||||
|
"Game Design",
|
||||||
|
"Spoilers.md",
|
||||||
|
"static",
|
||||||
|
"Stories/How Branching Stories Are Made.md",
|
||||||
|
"Stories/*/Coordinator Strategy.md",
|
||||||
|
"Stories/*/Branch Map.md",
|
||||||
|
],
|
||||||
|
// The vault splits its own lore by folder. Pre-Elysium is the default
|
||||||
|
// (question aetheria-pre-elysium-pin: late Sol); the pin is this one
|
||||||
|
// string.
|
||||||
|
default_era: "pre-elysium",
|
||||||
|
eras: &[
|
||||||
|
VaultEra {
|
||||||
|
id: "pre-elysium",
|
||||||
|
label: "Pre-Elysium",
|
||||||
|
description: "Late Sol, the Existential Collapse (2750-3025): aging infrastructure and institutions fail, wireheading is an industry, uploaded and uplifted minds hold unequal standing, powers fight over who survives; no FTL, no Elysium, no aether.",
|
||||||
|
withhold: &["Worldbuilding/Post-Elysium"],
|
||||||
|
},
|
||||||
|
era(
|
||||||
|
"post-elysium",
|
||||||
|
"Post-Elysium",
|
||||||
|
"After the Rupture: Sol's civilization displaced into Elysium, a sealed hostile domain; aether, espers, pseudospace, necrotech and spirits exist; old political habits survive with sharper tools.",
|
||||||
|
),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
// Eusocial Interbeing is the Zyphos setting (ruling vault-profile-zyphos);
|
||||||
|
// the Zyphos repository around it is machinery.
|
||||||
|
ProductionVault {
|
||||||
|
name: "zyphos",
|
||||||
|
root: "Zyphos/Eusocial Interbeing",
|
||||||
|
exclude: &["Game Design", "Inspirations"],
|
||||||
|
// The vault states no timeline: one present-day era.
|
||||||
|
default_era: "imperial-present",
|
||||||
|
eras: &[era(
|
||||||
|
"imperial-present",
|
||||||
|
"The Airawa Empire",
|
||||||
|
"The Airawa Empire rules a quarter of a continent through the Biological Memetic Engine; native nations resist; the Sa'ueia are nomads on another continent.",
|
||||||
|
)],
|
||||||
|
},
|
||||||
|
ProductionVault {
|
||||||
|
name: "delvehold",
|
||||||
|
root: "Delvehold/Delvehold",
|
||||||
|
exclude: &["Game Design", "Documentation"],
|
||||||
|
// The vault states no timeline: one present-day era.
|
||||||
|
default_era: "present",
|
||||||
|
eras: &[era(
|
||||||
|
"present",
|
||||||
|
"The Greathold now",
|
||||||
|
"The Greathold now: dwarven Holds in the Vaults of a mountain-range dungeon, at the start of a magical industrial revolution; delvers work dungeon contracts.",
|
||||||
|
)],
|
||||||
|
},
|
||||||
|
ProductionVault {
|
||||||
|
name: "avatar",
|
||||||
|
root: "Avatar",
|
||||||
|
exclude: &[],
|
||||||
|
// Humanity's waves are the spine. The vault does not partition notes
|
||||||
|
// by era, so no era withholds a path.
|
||||||
|
default_era: "rda-return",
|
||||||
|
eras: &[
|
||||||
|
era(
|
||||||
|
"contact",
|
||||||
|
"Contact (2130s-2140s)",
|
||||||
|
"The first wave: RDA mining, the Avatar Program, TAP, and the contact disease.",
|
||||||
|
),
|
||||||
|
era(
|
||||||
|
"first-war",
|
||||||
|
"The First War (2154)",
|
||||||
|
"Hometree falls, Toruk Makto unites the clans, and the RDA is expelled from Pandora.",
|
||||||
|
),
|
||||||
|
era(
|
||||||
|
"aftermath",
|
||||||
|
"Aftermath (2154-2168)",
|
||||||
|
"No RDA on Pandora; defectors live at Hell's Gate and Jake prepares for the return.",
|
||||||
|
),
|
||||||
|
era(
|
||||||
|
"rda-return",
|
||||||
|
"The RDA returns (2168-2169)",
|
||||||
|
"The second wave: the colonization mandate, the Bridgehead, and Ardmore.",
|
||||||
|
),
|
||||||
|
era(
|
||||||
|
"western-frontier-war",
|
||||||
|
"Western Frontier War (2169)",
|
||||||
|
"The western frontier war of 2169, in the second wave's colonization.",
|
||||||
|
),
|
||||||
|
era(
|
||||||
|
"reef-war",
|
||||||
|
"The Reef War (2169-2170)",
|
||||||
|
"The Metkayina reef clan, tulkun hunting, and the amrita the hunters want.",
|
||||||
|
),
|
||||||
|
era(
|
||||||
|
"fire-and-ash",
|
||||||
|
"Fire and Ash (2170 on)",
|
||||||
|
"Mangkwan, Varang, and a Na'vi-on-Na'vi war.",
|
||||||
|
),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
/// The eras `name` offers and the default among them, or `None` for a name
|
||||||
|
/// production does not serve.
|
||||||
|
pub fn production_eras(name: &str) -> Option<(&'static [VaultEra], &'static str)> {
|
||||||
|
let vault = PRODUCTION_VAULTS.iter().find(|vault| vault.name == name)?;
|
||||||
|
Some((vault.eras, vault.default_era))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The names of the vaults production serves.
|
||||||
|
pub fn production_vault_names() -> impl Iterator<Item = &'static str> {
|
||||||
|
PRODUCTION_VAULTS.iter().map(|vault| vault.name)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The production profile of `name`, rooted under `base`, or `None` for a name
|
||||||
|
/// production does not serve.
|
||||||
|
pub fn production_profile(name: &str, base: &Path) -> Option<VaultProfile> {
|
||||||
|
let vault = PRODUCTION_VAULTS.iter().find(|vault| vault.name == name)?;
|
||||||
|
Some(VaultProfile {
|
||||||
|
name: vault.name.into(),
|
||||||
|
root: base.join(vault.root),
|
||||||
|
exclude: vault.exclude.iter().map(|text| (*text).to_owned()).collect(),
|
||||||
|
..VaultProfile::default()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
/// The sha256, as lowercase hex, of the canonical encoding of the profile and
|
/// The sha256, as lowercase hex, of the canonical encoding of the profile and
|
||||||
/// the sorted `(path, sha256)` pairs of its admitted notes.
|
/// the sorted `(path, sha256)` pairs of its admitted notes.
|
||||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||||
|
|
@ -110,6 +267,16 @@ impl SnapshotId {
|
||||||
pub fn as_str(&self) -> &str {
|
pub fn as_str(&self) -> &str {
|
||||||
&self.0
|
&self.0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The id a stored name spells: sixty-four lowercase hex digits, nothing
|
||||||
|
/// that could name another path.
|
||||||
|
pub fn parse(text: &str) -> Result<Self, VaultError> {
|
||||||
|
if text.len() == 64 && text.bytes().all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f')) {
|
||||||
|
Ok(Self(text.to_owned()))
|
||||||
|
} else {
|
||||||
|
Err(VaultError::Corrupt)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl std::fmt::Display for SnapshotId {
|
impl std::fmt::Display for SnapshotId {
|
||||||
|
|
@ -335,6 +502,52 @@ impl VaultSnapshot {
|
||||||
read
|
read
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Records this snapshot as the one `profile`'s last import produced: the
|
||||||
|
/// file `<profile>.current` in the store holds its id. The server reads
|
||||||
|
/// this pointer and never a vault directory; only an importer writes it.
|
||||||
|
pub fn record_current(&self, directory: &Path) -> Result<(), VaultError> {
|
||||||
|
let path = current_path(directory, &self.profile.name)?;
|
||||||
|
let partial = directory.join(format!("{}.current.{}.partial", self.profile.name, unique_suffix()));
|
||||||
|
let written = std::fs::write(&partial, self.id.as_str())
|
||||||
|
.and_then(|()| std::fs::rename(&partial, &path).or_else(|_| {
|
||||||
|
let _ = std::fs::remove_file(&path);
|
||||||
|
std::fs::rename(&partial, &path)
|
||||||
|
}))
|
||||||
|
.map_err(|_| VaultError::Store);
|
||||||
|
let _ = std::fs::remove_file(&partial);
|
||||||
|
written
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The id the last import of `profile` recorded in `directory`.
|
||||||
|
pub fn current_id(directory: &Path, profile: &str) -> Result<SnapshotId, VaultError> {
|
||||||
|
let text = std::fs::read_to_string(current_path(directory, profile)?)
|
||||||
|
.map_err(|_| VaultError::NotImported)?;
|
||||||
|
SnapshotId::parse(text.trim())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A deterministic premise for a seed given no brief: the first
|
||||||
|
/// `MAX_EXCERPT_CHARS` of the vault's entry note. The entry note is the
|
||||||
|
/// shallowest `index` note, else the shallowest note named for the
|
||||||
|
/// vault's scope or title, else the first note by path; a vault of no
|
||||||
|
/// notes has none.
|
||||||
|
pub fn premise(&self) -> Option<String> {
|
||||||
|
let depth = |note: &&SnapshotNote| note.reference.matches('/').count();
|
||||||
|
let stem = |note: &SnapshotNote| {
|
||||||
|
Path::new(¬e.reference)
|
||||||
|
.file_stem()
|
||||||
|
.map(|value| value.to_string_lossy().to_lowercase())
|
||||||
|
.unwrap_or_default()
|
||||||
|
};
|
||||||
|
let entry = self
|
||||||
|
.notes
|
||||||
|
.iter()
|
||||||
|
.filter(|note| stem(note) == "index")
|
||||||
|
.min_by_key(|note| depth(note))
|
||||||
|
.or_else(|| self.notes.iter().min_by_key(|note| depth(note)))?;
|
||||||
|
let text: String = entry.body.trim().chars().take(MAX_EXCERPT_CHARS).collect();
|
||||||
|
(!text.is_empty()).then_some(text)
|
||||||
|
}
|
||||||
|
|
||||||
fn read_row(copy: &Path, id: &SnapshotId) -> Result<Self, VaultError> {
|
fn read_row(copy: &Path, id: &SnapshotId) -> Result<Self, VaultError> {
|
||||||
let store = OwnedRedbMessagePackBackingStore::new(copy).map_err(|_| VaultError::Corrupt)?;
|
let store = OwnedRedbMessagePackBackingStore::new(copy).map_err(|_| VaultError::Corrupt)?;
|
||||||
let rows = store.pull_all().map_err(|_| VaultError::Corrupt)?;
|
let rows = store.pull_all().map_err(|_| VaultError::Corrupt)?;
|
||||||
|
|
@ -363,6 +576,17 @@ fn unique_suffix() -> String {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The lock file the store leaves beside the file it opened.
|
/// The lock file the store leaves beside the file it opened.
|
||||||
|
/// `<profile>.current` in a store directory. A profile name is lowercase
|
||||||
|
/// ASCII letters, digits and hyphens: it is a file name and never a path.
|
||||||
|
fn current_path(directory: &Path, profile: &str) -> Result<PathBuf, VaultError> {
|
||||||
|
if profile.is_empty()
|
||||||
|
|| !profile.bytes().all(|byte| matches!(byte, b'a'..=b'z' | b'0'..=b'9' | b'-'))
|
||||||
|
{
|
||||||
|
return Err(VaultError::NotImported);
|
||||||
|
}
|
||||||
|
Ok(directory.join(format!("{profile}.current")))
|
||||||
|
}
|
||||||
|
|
||||||
fn sidecar(path: &Path) -> PathBuf {
|
fn sidecar(path: &Path) -> PathBuf {
|
||||||
let mut name = path.as_os_str().to_owned();
|
let mut name = path.as_os_str().to_owned();
|
||||||
name.push(".lock");
|
name.push(".lock");
|
||||||
|
|
@ -536,12 +760,17 @@ impl VaultEvidenceSource {
|
||||||
/// tier is a directory in every vault that has one, so it is expressed as a
|
/// tier is a directory in every vault that has one, so it is expressed as a
|
||||||
/// scope and there is no tier field anywhere in this file. `..`, an
|
/// scope and there is no tier field anywhere in this file. `..`, an
|
||||||
/// absolute scope, and a scope that holds no note are refused.
|
/// absolute scope, and a scope that holds no note are refused.
|
||||||
pub fn from_snapshot(snapshot: &VaultSnapshot, scope: &str) -> Result<Self, VaultError> {
|
///
|
||||||
|
/// A note under any vault-relative path in `withhold` is not admitted, so
|
||||||
|
/// retrieval cannot return it; a world set in an era passes that era's
|
||||||
|
/// withheld lore here and every other caller passes none.
|
||||||
|
pub fn from_snapshot(snapshot: &VaultSnapshot, scope: &str, withhold: &[&str]) -> Result<Self, VaultError> {
|
||||||
let scope = relative_dir(scope).ok_or_else(|| VaultError::Scope(scope.to_owned()))?;
|
let scope = relative_dir(scope).ok_or_else(|| VaultError::Scope(scope.to_owned()))?;
|
||||||
let notes: Vec<SnapshotNote> = snapshot
|
let notes: Vec<SnapshotNote> = snapshot
|
||||||
.notes
|
.notes
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|note| scope.is_empty() || is_under(¬e.reference, &scope))
|
.filter(|note| scope.is_empty() || is_under(¬e.reference, &scope))
|
||||||
|
.filter(|note| !withhold.iter().any(|path| is_under(¬e.reference, path)))
|
||||||
.cloned()
|
.cloned()
|
||||||
.collect();
|
.collect();
|
||||||
if notes.is_empty() && !scope.is_empty() {
|
if notes.is_empty() && !scope.is_empty() {
|
||||||
|
|
@ -841,7 +1070,7 @@ mod tests {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn open(root: &Path, scope: &str) -> Result<VaultEvidenceSource, VaultError> {
|
fn open(root: &Path, scope: &str) -> Result<VaultEvidenceSource, VaultError> {
|
||||||
VaultEvidenceSource::from_snapshot(&VaultSnapshot::build(&profile(root))?, scope)
|
VaultEvidenceSource::from_snapshot(&VaultSnapshot::build(&profile(root))?, scope, &[])
|
||||||
}
|
}
|
||||||
|
|
||||||
fn fixture() -> tempfile::TempDir {
|
fn fixture() -> tempfile::TempDir {
|
||||||
|
|
@ -1280,7 +1509,7 @@ mod tests {
|
||||||
async fn live_edits_do_not_reach_a_snapshot() {
|
async fn live_edits_do_not_reach_a_snapshot() {
|
||||||
let vault = fixture();
|
let vault = fixture();
|
||||||
let built = snapshot(vault.path());
|
let built = snapshot(vault.path());
|
||||||
let source = VaultEvidenceSource::from_snapshot(&built, "").unwrap();
|
let source = VaultEvidenceSource::from_snapshot(&built, "", &[]).unwrap();
|
||||||
let ask = || query(&["Rain Gate#Tolls", "Low Sere", "Provenance"]);
|
let ask = || query(&["Rain Gate#Tolls", "Low Sere", "Provenance"]);
|
||||||
let before = source.retrieve(&ask()).await.unwrap();
|
let before = source.retrieve(&ask()).await.unwrap();
|
||||||
|
|
||||||
|
|
@ -1293,7 +1522,7 @@ mod tests {
|
||||||
for (b, a) in before.iter().zip(&after) {
|
for (b, a) in before.iter().zip(&after) {
|
||||||
assert_eq!((&b.reference, &b.excerpt, &b.source), (&a.reference, &a.excerpt, &a.source));
|
assert_eq!((&b.reference, &b.excerpt, &b.source), (&a.reference, &a.excerpt, &a.source));
|
||||||
}
|
}
|
||||||
let rebuilt = VaultEvidenceSource::from_snapshot(&built, "").unwrap();
|
let rebuilt = VaultEvidenceSource::from_snapshot(&built, "", &[]).unwrap();
|
||||||
assert!(rebuilt.retrieve(&query(&["New"])).await.unwrap().is_empty());
|
assert!(rebuilt.retrieve(&query(&["New"])).await.unwrap().is_empty());
|
||||||
assert_ne!(snapshot(vault.path()).id(), built.id());
|
assert_ne!(snapshot(vault.path()).id(), built.id());
|
||||||
}
|
}
|
||||||
|
|
@ -1530,12 +1759,12 @@ mod tests {
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
let built = snapshot(vault.path());
|
let built = snapshot(vault.path());
|
||||||
assert!(matches!(VaultEvidenceSource::from_snapshot(&built, "Nowhere"), Err(VaultError::Scope(_))));
|
assert!(matches!(VaultEvidenceSource::from_snapshot(&built, "Nowhere", &[]), Err(VaultError::Scope(_))));
|
||||||
assert!(VaultEvidenceSource::from_snapshot(&built, "Spoilers").is_ok());
|
assert!(VaultEvidenceSource::from_snapshot(&built, "Spoilers", &[]).is_ok());
|
||||||
let empty = tempfile::tempdir().unwrap();
|
let empty = tempfile::tempdir().unwrap();
|
||||||
assert!(VaultEvidenceSource::from_snapshot(&snapshot(empty.path()), "").is_ok());
|
assert!(VaultEvidenceSource::from_snapshot(&snapshot(empty.path()), "", &[]).is_ok());
|
||||||
assert!(matches!(
|
assert!(matches!(
|
||||||
VaultEvidenceSource::from_snapshot(&snapshot(empty.path()), "Spoilers"),
|
VaultEvidenceSource::from_snapshot(&snapshot(empty.path()), "Spoilers", &[]),
|
||||||
Err(VaultError::Scope(_))
|
Err(VaultError::Scope(_))
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
@ -1683,37 +1912,76 @@ mod tests {
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The import records which snapshot a profile last produced; the server
|
||||||
|
/// reads that record and nothing else. A name that is not a file name, or a
|
||||||
|
/// record that is not an id, is refused.
|
||||||
|
#[test]
|
||||||
|
fn an_import_records_its_snapshot_as_the_profiles_current_one() {
|
||||||
|
let vault = fixture();
|
||||||
|
let built = snapshot(vault.path());
|
||||||
|
let store = tempfile::tempdir().unwrap();
|
||||||
|
built.import_into(store.path()).unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
VaultSnapshot::current_id(store.path(), "fixture"),
|
||||||
|
Err(VaultError::NotImported)
|
||||||
|
));
|
||||||
|
built.record_current(store.path()).unwrap();
|
||||||
|
built.record_current(store.path()).unwrap();
|
||||||
|
assert_eq!(&VaultSnapshot::current_id(store.path(), "fixture").unwrap(), built.id());
|
||||||
|
for name in ["", "../fixture", "Fixture", "a/b"] {
|
||||||
|
assert!(
|
||||||
|
matches!(VaultSnapshot::current_id(store.path(), name), Err(VaultError::NotImported)),
|
||||||
|
"{name:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
std::fs::write(store.path().join("fixture.current"), "../../etc/passwd").unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
VaultSnapshot::current_id(store.path(), "fixture"),
|
||||||
|
Err(VaultError::Corrupt)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The seed's premise is the shallowest index note's opening, bounded.
|
||||||
|
#[test]
|
||||||
|
fn the_premise_is_the_entry_notes_opening() {
|
||||||
|
let vault = fixture();
|
||||||
|
assert_eq!(snapshot(vault.path()).premise().as_deref(), Some("Public index."));
|
||||||
|
let long = tempfile::tempdir().unwrap();
|
||||||
|
write(long.path(), "Zed.md", &"x".repeat(MAX_EXCERPT_CHARS + 50));
|
||||||
|
assert_eq!(snapshot(long.path()).premise().unwrap().chars().count(), MAX_EXCERPT_CHARS);
|
||||||
|
let empty = tempfile::tempdir().unwrap();
|
||||||
|
assert_eq!(snapshot(empty.path()).premise(), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The production table is the one place a profile is written: Zyphos is
|
||||||
|
/// Eusocial Interbeing without its design and inspiration folders, and
|
||||||
|
/// every name is a valid pointer name.
|
||||||
|
#[test]
|
||||||
|
fn the_production_table_names_four_vaults_rooted_under_the_hosts_base() {
|
||||||
|
let base = Path::new("/vaults");
|
||||||
|
assert_eq!(
|
||||||
|
production_vault_names().collect::<Vec<_>>(),
|
||||||
|
["aetheria", "zyphos", "delvehold", "avatar"]
|
||||||
|
);
|
||||||
|
let zyphos = production_profile("zyphos", base).unwrap();
|
||||||
|
assert_eq!(zyphos.root, base.join("Zyphos/Eusocial Interbeing"));
|
||||||
|
assert_eq!(zyphos.exclude, ["Game Design", "Inspirations"]);
|
||||||
|
assert!(production_profile("nowhere", base).is_none());
|
||||||
|
let store = Path::new("/store");
|
||||||
|
for name in production_vault_names() {
|
||||||
|
assert!(current_path(store, name).is_ok(), "{name}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Real vaults, read-only. `GHOSTLIGHT_VAULT_SMOKE` names a directory that
|
/// Real vaults, read-only. `GHOSTLIGHT_VAULT_SMOKE` names a directory that
|
||||||
/// holds byte-for-byte copies of `AetheriaLore`, `Zyphos` and `Delvehold`.
|
/// holds byte-for-byte copies of `AetheriaLore`, `Zyphos`, `Delvehold` and
|
||||||
|
/// `Avatar`, laid out as the production table's roots expect.
|
||||||
#[test]
|
#[test]
|
||||||
#[ignore = "needs the real vaults"]
|
#[ignore = "needs the real vaults"]
|
||||||
fn real_vaults_build() {
|
fn real_vaults_build() {
|
||||||
let base = PathBuf::from(std::env::var("GHOSTLIGHT_VAULT_SMOKE").unwrap());
|
let base = PathBuf::from(std::env::var("GHOSTLIGHT_VAULT_SMOKE").unwrap());
|
||||||
let cases = [
|
for name in production_vault_names() {
|
||||||
(
|
let profile = production_profile(name, &base).unwrap();
|
||||||
"aetheria",
|
|
||||||
"AetheriaLore/Aetheria",
|
|
||||||
vec![
|
|
||||||
"Brainstorming",
|
|
||||||
"Game Design",
|
|
||||||
"Spoilers.md",
|
|
||||||
"static",
|
|
||||||
"Stories/How Branching Stories Are Made.md",
|
|
||||||
"Stories/*/Coordinator Strategy.md",
|
|
||||||
"Stories/*/Branch Map.md",
|
|
||||||
],
|
|
||||||
),
|
|
||||||
("zyphos", "Zyphos/Eusocial Interbeing", vec!["Game Design", "Inspirations"]),
|
|
||||||
("delvehold", "Delvehold/Delvehold", vec!["Game Design", "Documentation"]),
|
|
||||||
("avatar", "Avatar", vec![]),
|
|
||||||
];
|
|
||||||
for (name, relative, exclude) in cases {
|
|
||||||
let profile = VaultProfile {
|
|
||||||
name: name.into(),
|
|
||||||
root: base.join(relative),
|
|
||||||
exclude: exclude.into_iter().map(str::to_owned).collect(),
|
|
||||||
..VaultProfile::default()
|
|
||||||
};
|
|
||||||
let built = VaultSnapshot::build(&profile).unwrap();
|
let built = VaultSnapshot::build(&profile).unwrap();
|
||||||
let again = VaultSnapshot::build(&profile).unwrap();
|
let again = VaultSnapshot::build(&profile).unwrap();
|
||||||
assert_eq!(built.id(), again.id());
|
assert_eq!(built.id(), again.id());
|
||||||
|
|
@ -1727,4 +1995,50 @@ mod tests {
|
||||||
println!("SMOKE {name} notes={} id={}", built.note_count(), built.id());
|
println!("SMOKE {name} notes={} id={}", built.note_count(), built.id());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Spec test: a note under a withheld path is not admitted to the source,
|
||||||
|
/// so retrieval for it returns nothing; with nothing withheld it returns
|
||||||
|
/// the note. A link into withheld lore is not followed either.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn withheld_lore_is_not_evidence() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let root = directory.path();
|
||||||
|
write(root, "Worldbuilding/Post-Elysium/Aether.md", "The aether answers espers.\n");
|
||||||
|
write(root, "Worldbuilding/Pre-Elysium/Collapse.md", "The grid fails.\n");
|
||||||
|
let built = snapshot(root);
|
||||||
|
|
||||||
|
let withheld = VaultEvidenceSource::from_snapshot(&built, "", &["Worldbuilding/Post-Elysium"]).unwrap();
|
||||||
|
assert!(withheld.retrieve(&query(&["Aether"])).await.unwrap().is_empty());
|
||||||
|
let collapse = withheld.retrieve(&query(&["Collapse"])).await.unwrap();
|
||||||
|
assert!(collapse.iter().all(|receipt| !format!("{:?}", receipt.reference).contains("Post-Elysium")));
|
||||||
|
|
||||||
|
let open = VaultEvidenceSource::from_snapshot(&built, "", &[]).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
open.retrieve(&query(&["Aether"])).await.unwrap()[0].reference,
|
||||||
|
EvidenceRef::new("Worldbuilding/Post-Elysium/Aether.md")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Spec test: every production vault offers at least one era, with unique
|
||||||
|
/// kebab ids, a default that names one of them, and a description each.
|
||||||
|
#[test]
|
||||||
|
fn every_production_vault_has_a_coherent_era_table() {
|
||||||
|
for name in production_vault_names() {
|
||||||
|
let (eras, default) = production_eras(name).expect("a served vault has an era table");
|
||||||
|
assert!(!eras.is_empty(), "{name}");
|
||||||
|
assert!(eras.iter().any(|era| era.id == default), "{name} default {default}");
|
||||||
|
let mut seen = std::collections::BTreeSet::new();
|
||||||
|
for era in eras {
|
||||||
|
assert!(seen.insert(era.id), "{name}: duplicate era {}", era.id);
|
||||||
|
assert!(
|
||||||
|
!era.id.is_empty() && era.id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-'),
|
||||||
|
"{name}: {} is not kebab",
|
||||||
|
era.id
|
||||||
|
);
|
||||||
|
assert!(!era.label.is_empty() && !era.description.is_empty(), "{name}/{}", era.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert!(production_eras("nowhere").is_none());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -135,6 +135,7 @@ impl CreateVerseWorldIntent {
|
||||||
},
|
},
|
||||||
lens_weights: self.lens_weights,
|
lens_weights: self.lens_weights,
|
||||||
grammar: Some(self.catalog.grammar),
|
grammar: Some(self.catalog.grammar),
|
||||||
|
era: None,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -344,6 +344,7 @@ async fn the_dungeon_ingress_still_creates_an_unbound_world() {
|
||||||
targets: BTreeMap::new(),
|
targets: BTreeMap::new(),
|
||||||
jurisdictions: Vec::new(),
|
jurisdictions: Vec::new(),
|
||||||
lens_weights: stock_weights(),
|
lens_weights: stock_weights(),
|
||||||
|
era: None,
|
||||||
},
|
},
|
||||||
&principal,
|
&principal,
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -57,6 +57,7 @@ impl World {
|
||||||
// An external crate has no library fixture; it states its
|
// An external crate has no library fixture; it states its
|
||||||
// own weights, as every consumer must.
|
// own weights, as every consumer must.
|
||||||
lens_weights: LensWeights::new(BTreeMap::from([(Lens::Patina, 1)])),
|
lens_weights: LensWeights::new(BTreeMap::from([(Lens::Patina, 1)])),
|
||||||
|
era: None,
|
||||||
},
|
},
|
||||||
&principal,
|
&principal,
|
||||||
)
|
)
|
||||||
|
|
|
||||||
120
deployment/idunn/recipe.toml
Normal file
|
|
@ -0,0 +1,120 @@
|
||||||
|
schema = "gamecult.idunn.target_declaration.v1"
|
||||||
|
target = "ghostlight"
|
||||||
|
source_stamp_environment = "GHOSTLIGHT_BUILD_COMMIT"
|
||||||
|
|
||||||
|
# The Dungeon is one binary: the page is compiled into it, so there is no
|
||||||
|
# adjacent artifact. The connector key is not declared here: the operator
|
||||||
|
# binding's [workload.secret_files] entry GHOSTLIGHT_CONNECTOR_KEY_FILE is what
|
||||||
|
# Idunn loads as a systemd credential, and the recipe only names the variable
|
||||||
|
# that then holds the credential's path.
|
||||||
|
|
||||||
|
[[steps]]
|
||||||
|
id = "test-dungeon"
|
||||||
|
phase = "test"
|
||||||
|
runner = "rust-build"
|
||||||
|
required_environment = ["CARGO_HOME", "HOME"]
|
||||||
|
argv = ["cargo", "test", "--locked", "-p", "ghostlight-dungeon", "--bin", "ghostlight-dungeon"]
|
||||||
|
|
||||||
|
[[steps]]
|
||||||
|
id = "build-daemon"
|
||||||
|
phase = "build"
|
||||||
|
runner = "rust-build"
|
||||||
|
required_environment = ["CARGO_HOME", "HOME"]
|
||||||
|
argv = ["cargo", "build", "--locked", "--release", "-p", "ghostlight-dungeon", "--bin", "ghostlight-dungeon"]
|
||||||
|
|
||||||
|
[[artifacts]]
|
||||||
|
id = "ghostlight-dungeon"
|
||||||
|
source_kind = "runner-output"
|
||||||
|
runner = "rust-build"
|
||||||
|
source = "target/release/ghostlight-dungeon"
|
||||||
|
destination = "ghostlight-dungeon"
|
||||||
|
executable = true
|
||||||
|
|
||||||
|
[service]
|
||||||
|
executable_artifact = "ghostlight-dungeon"
|
||||||
|
arguments = [
|
||||||
|
{ kind = "literal", value = "--state-root" },
|
||||||
|
{ kind = "binding", name = "state_root" },
|
||||||
|
]
|
||||||
|
transport = "http"
|
||||||
|
route_required = true
|
||||||
|
required_environment = [
|
||||||
|
"GAMECULT_IDUNN_CANDIDATE_BIND",
|
||||||
|
"GAMECULT_IDUNN_PROCESS_WRITE_LEASE",
|
||||||
|
"GAMECULT_IDUNN_RUNTIME_BUNDLE",
|
||||||
|
"GHOSTLIGHT_CONNECTOR_ADDR",
|
||||||
|
"GHOSTLIGHT_CONNECTOR_KEY_FILE",
|
||||||
|
"GHOSTLIGHT_HEIMDALL_APP_SECRET_FILE",
|
||||||
|
"GHOSTLIGHT_HEIMDALL_BASE_URL",
|
||||||
|
"GHOSTLIGHT_PUBLIC_APP_URL",
|
||||||
|
"GHOSTLIGHT_SESSION_WRAPPING_KEY_FILE",
|
||||||
|
]
|
||||||
|
optional_environment = [
|
||||||
|
"GHOSTLIGHT_AUTH_PROVIDERS",
|
||||||
|
"GHOSTLIGHT_CONTROLLER_ELABORATOR_MODEL",
|
||||||
|
"GHOSTLIGHT_CONTROLLER_INTERPRETER_MODEL",
|
||||||
|
"GHOSTLIGHT_CONTROLLER_MAX_CONCURRENT",
|
||||||
|
"GHOSTLIGHT_CONTROLLER_OPERATIONAL_MODEL",
|
||||||
|
"GHOSTLIGHT_CONTROLLER_PERSONA_MODEL",
|
||||||
|
"GHOSTLIGHT_CONTROLLER_PROJECTOR_MODEL",
|
||||||
|
"GHOSTLIGHT_PLAY_MODEL",
|
||||||
|
"RUST_LOG",
|
||||||
|
]
|
||||||
|
|
||||||
|
[service.health]
|
||||||
|
contract = "ghostlight.cultnet-rudp-service-health"
|
||||||
|
|
||||||
|
# Idunn's state kinds are files. The snapshots and timelines slots are
|
||||||
|
# directories the daemon owns; they are declared as opaque process-owned paths
|
||||||
|
# (external-file), which Idunn preserves and never interprets.
|
||||||
|
[state]
|
||||||
|
schema_generation = "dungeon-v1"
|
||||||
|
|
||||||
|
[[state.slots]]
|
||||||
|
id = "catalog"
|
||||||
|
relative_path = "catalog.cc"
|
||||||
|
kind = "cultcache-file"
|
||||||
|
schema = "ghostlight.dungeon_catalog.v1"
|
||||||
|
writer = "process-bound-single-writer"
|
||||||
|
recovery = "preserve"
|
||||||
|
startup = "create-or-open-after-write-lease"
|
||||||
|
|
||||||
|
[[state.slots]]
|
||||||
|
id = "app-sessions"
|
||||||
|
relative_path = "service/app-sessions-v2.cc"
|
||||||
|
kind = "cultcache-file"
|
||||||
|
schema = "ghostlight.app_session_store.v2"
|
||||||
|
writer = "process-bound-single-writer"
|
||||||
|
recovery = "preserve"
|
||||||
|
startup = "create-or-open-after-write-lease"
|
||||||
|
|
||||||
|
[[state.slots]]
|
||||||
|
id = "snapshots"
|
||||||
|
relative_path = "snapshots"
|
||||||
|
kind = "external-file"
|
||||||
|
schema = "ghostlight.vault_snapshot.v1"
|
||||||
|
writer = "process-bound-single-writer"
|
||||||
|
recovery = "rebuildable"
|
||||||
|
startup = "create-or-open-after-write-lease"
|
||||||
|
|
||||||
|
[[state.slots]]
|
||||||
|
id = "timelines"
|
||||||
|
relative_path = "timelines"
|
||||||
|
kind = "external-file"
|
||||||
|
schema = "ghostlight.world_state.consumer.v6"
|
||||||
|
writer = "process-bound-single-writer"
|
||||||
|
recovery = "preserve"
|
||||||
|
startup = "create-or-open-after-write-lease"
|
||||||
|
|
||||||
|
[[provides]]
|
||||||
|
capability = "ghostlight.world-service"
|
||||||
|
schema = "ghostlight.world_state.consumer.v6"
|
||||||
|
compatibility = "consumer-v6"
|
||||||
|
|
||||||
|
# Heimdall is found through Odin at use, not declared as an Idunn dependency.
|
||||||
|
[[dependencies]]
|
||||||
|
kind = "shared-infrastructure"
|
||||||
|
capability = "odin.verse-rendezvous"
|
||||||
|
schema = "odin.verse-topology.v1"
|
||||||
|
compatibility = "v1"
|
||||||
|
startup = "before-promotion"
|
||||||
BIN
probes/page/01-signin-desktop.png
Normal file
|
After Width: | Height: | Size: 25 KiB |
BIN
probes/page/01-signin-phone.png
Normal file
|
After Width: | Height: | Size: 64 KiB |
BIN
probes/page/02-worlds-empty-desktop.png
Normal file
|
After Width: | Height: | Size: 16 KiB |
BIN
probes/page/02-worlds-empty-phone.png
Normal file
|
After Width: | Height: | Size: 41 KiB |
BIN
probes/page/03-begin-desktop.png
Normal file
|
After Width: | Height: | Size: 40 KiB |
BIN
probes/page/03-begin-phone.png
Normal file
|
After Width: | Height: | Size: 91 KiB |
BIN
probes/page/04-ready-desktop.png
Normal file
|
After Width: | Height: | Size: 22 KiB |
BIN
probes/page/04-ready-phone.png
Normal file
|
After Width: | Height: | Size: 49 KiB |
BIN
probes/page/05-narration-desktop.png
Normal file
|
After Width: | Height: | Size: 56 KiB |
BIN
probes/page/05-narration-phone.png
Normal file
|
After Width: | Height: | Size: 127 KiB |
BIN
probes/page/06-question-desktop.png
Normal file
|
After Width: | Height: | Size: 68 KiB |
BIN
probes/page/06-question-phone.png
Normal file
|
After Width: | Height: | Size: 137 KiB |
BIN
probes/page/07-answered-scrollback-desktop.png
Normal file
|
After Width: | Height: | Size: 74 KiB |
BIN
probes/page/07-answered-scrollback-phone.png
Normal file
|
After Width: | Height: | Size: 128 KiB |
BIN
probes/page/08-fault-retry-desktop.png
Normal file
|
After Width: | Height: | Size: 66 KiB |
BIN
probes/page/08-fault-retry-phone.png
Normal file
|
After Width: | Height: | Size: 111 KiB |
BIN
probes/page/09-fault-after-retry-desktop.png
Normal file
|
After Width: | Height: | Size: 61 KiB |
BIN
probes/page/09-fault-after-retry-phone.png
Normal file
|
After Width: | Height: | Size: 117 KiB |
BIN
probes/page/10-refusal-line-desktop.png
Normal file
|
After Width: | Height: | Size: 62 KiB |
BIN
probes/page/10-refusal-line-phone.png
Normal file
|
After Width: | Height: | Size: 115 KiB |
BIN
probes/page/11-worlds-seeding-failed-ready-desktop.png
Normal file
|
After Width: | Height: | Size: 37 KiB |
BIN
probes/page/11-worlds-seeding-failed-ready-phone.png
Normal file
|
After Width: | Height: | Size: 91 KiB |
BIN
probes/page/12-seeding-progress-desktop.png
Normal file
|
After Width: | Height: | Size: 18 KiB |
BIN
probes/page/12-seeding-progress-phone.png
Normal file
|
After Width: | Height: | Size: 45 KiB |
BIN
probes/page/13-history-live-360.png
Normal file
|
After Width: | Height: | Size: 102 KiB |
BIN
probes/page/14-history-after-reload-360.png
Normal file
|
After Width: | Height: | Size: 102 KiB |
BIN
probes/page/15-history-older-loaded-360.png
Normal file
|
After Width: | Height: | Size: 98 KiB |
BIN
probes/page/16-second-context-360.png
Normal file
|
After Width: | Height: | Size: 102 KiB |
BIN
probes/page/17-second-context-older-loaded-360.png
Normal file
|
After Width: | Height: | Size: 98 KiB |
BIN
probes/page/18-begin-era-lenses-360.png
Normal file
|
After Width: | Height: | Size: 307 KiB |
BIN
probes/page/19-begin-post-elysium-charter3-veil0-360.png
Normal file
|
After Width: | Height: | Size: 312 KiB |
76
probes/page/begin-era.mjs
Normal file
|
|
@ -0,0 +1,76 @@
|
||||||
|
// Drives the Begin page at 360 px: serves the page's real files over a stub API shaped like the
|
||||||
|
// real /api/vaults (the production era tables) and records the Begin request the page sends.
|
||||||
|
// usage: node begin-era.mjs <page-dir> <out-dir> [chrome-path]
|
||||||
|
import http from "node:http";
|
||||||
|
import { readFileSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
|
||||||
|
import { spawn } from "node:child_process";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { join } from "node:path";
|
||||||
|
const [pageDir, out, chrome = "C:/Program Files/Google/Chrome/Application/chrome.exe"] = process.argv.slice(2);
|
||||||
|
mkdirSync(out, { recursive: true });
|
||||||
|
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||||
|
const lenses = [
|
||||||
|
["patina", "Patina", "ordinary objects, customs, nicknames, local jokes"], ["charter", "Charter", "government, law, offices, selection, succession, redress"],
|
||||||
|
["ledger", "Ledger", "resources, labor, trade, infrastructure, scarcity, class pressure"], ["hearth", "Hearth", "kinship, daily life, care, obligation, belonging"],
|
||||||
|
["tangle", "Tangle", "factions, alliances, rivalries, leverage"], ["veil", "Veil", "secrets, rumors, misinformation, taboos, unevenly held knowledge"],
|
||||||
|
["ember", "Ember", "disputes, hazards, instability, escalation, urgent pressure"], ["numen", "Numen", "religion, magic, ritual, awe, cosmology, the genuinely strange"],
|
||||||
|
].map(([id, name, reaches_for]) => ({ id, name, reaches_for }));
|
||||||
|
const vaults = [
|
||||||
|
{ name: "aetheria", default_era: "pre-elysium", eras: [
|
||||||
|
{ id: "pre-elysium", label: "Pre-Elysium", description: "Late Sol, the Existential Collapse (2750-3025): aging infrastructure and institutions fail, wireheading is an industry, uploaded and uplifted minds hold unequal standing, powers fight over who survives; no FTL, no Elysium, no aether." },
|
||||||
|
{ id: "post-elysium", label: "Post-Elysium", description: "After the Rupture: Sol's civilization displaced into Elysium, a sealed hostile domain; aether, espers, pseudospace, necrotech and spirits exist; old political habits survive with sharper tools." } ] },
|
||||||
|
{ name: "delvehold", default_era: "present", eras: [{ id: "present", label: "The Greathold now", description: "x" }] },
|
||||||
|
];
|
||||||
|
let begun = null;
|
||||||
|
const server = http.createServer((req, res) => {
|
||||||
|
const send = (code, type, body) => { res.writeHead(code, { "content-type": type }); res.end(body); };
|
||||||
|
const json = (b, c = 200) => send(c, "application/json", JSON.stringify(b));
|
||||||
|
const u = new URL(req.url, "http://x");
|
||||||
|
if (u.pathname === "/api/me") return json({ signedIn: true, currentTimeline: null, providers: [] });
|
||||||
|
if (u.pathname === "/api/timelines") return json({ timelines: [] });
|
||||||
|
if (u.pathname === "/api/vaults") return json({ vaults, lenses });
|
||||||
|
if (u.pathname === "/api/begin") { let b = ""; req.on("data", (d) => (b += d)); req.on("end", () => { begun = JSON.parse(b); json({ error: "stub: no kernel behind this probe", step: "open" }, 409); }); return; }
|
||||||
|
const file = { "/": "index.html", "/index.html": "index.html", "/page.css": "page.css", "/page.js": "page.js" }[u.pathname];
|
||||||
|
if (!file) return json({}, 404);
|
||||||
|
send(200, file.endsWith("css") ? "text/css" : file.endsWith("js") ? "text/javascript" : "text/html", readFileSync(join(pageDir, file)));
|
||||||
|
});
|
||||||
|
await new Promise((r) => server.listen(0, "127.0.0.1", r));
|
||||||
|
const base = `http://127.0.0.1:${server.address().port}/`;
|
||||||
|
const port = 9300 + Math.floor(Math.random() * 500);
|
||||||
|
const proc = spawn(chrome, ["--headless=new", `--remote-debugging-port=${port}`, `--user-data-dir=${mkdtempSync(join(tmpdir(), "era-"))}`, "--no-first-run", "about:blank"], { stdio: "ignore" });
|
||||||
|
let targets;
|
||||||
|
for (let i = 0; i < 50; i++) { try { targets = await (await fetch(`http://127.0.0.1:${port}/json`)).json(); break; } catch { await sleep(200); } }
|
||||||
|
const ws = new WebSocket(targets.find((t) => t.type === "page").webSocketDebuggerUrl);
|
||||||
|
await new Promise((r) => (ws.onopen = r));
|
||||||
|
let id = 0; const waiting = new Map();
|
||||||
|
ws.onmessage = (m) => { const d = JSON.parse(m.data); if (d.id && waiting.has(d.id)) waiting.get(d.id)(d); };
|
||||||
|
const cdp = (method, params = {}) => new Promise((r) => { const n = ++id; waiting.set(n, r); ws.send(JSON.stringify({ id: n, method, params })); });
|
||||||
|
const evalJs = async (expression) => (await cdp("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true })).result?.result?.value;
|
||||||
|
const shot = async (name) => {
|
||||||
|
const h = await evalJs("document.documentElement.scrollHeight");
|
||||||
|
await cdp("Emulation.setDeviceMetricsOverride", { width: 360, height: h, deviceScaleFactor: 2, mobile: true });
|
||||||
|
const r = await cdp("Page.captureScreenshot", { format: "png" });
|
||||||
|
writeFileSync(join(out, name), Buffer.from(r.result.data, "base64"));
|
||||||
|
};
|
||||||
|
await cdp("Page.enable");
|
||||||
|
await cdp("Emulation.setDeviceMetricsOverride", { width: 360, height: 800, deviceScaleFactor: 2, mobile: true });
|
||||||
|
await cdp("Page.navigate", { url: base });
|
||||||
|
await sleep(800);
|
||||||
|
await evalJs("document.querySelector('.btn.wide').click()"); await sleep(600);
|
||||||
|
await shot("18-begin-era-lenses-360.png");
|
||||||
|
const overflow = await evalJs("document.documentElement.scrollWidth > document.documentElement.clientWidth");
|
||||||
|
// pick Post-Elysium, then back to default; set Charter 3, Veil 0
|
||||||
|
await evalJs("document.querySelector('input[name=era][value=post-elysium]').click()");
|
||||||
|
await evalJs(`(() => { const rows=[...document.querySelectorAll('.lens')]; const f=(n)=>rows.find(r=>r.textContent.startsWith(n)); const plus=f('Charter').querySelectorAll('.step')[1]; plus.click(); plus.click(); f('Veil').querySelectorAll('.step')[0].click(); })()`);
|
||||||
|
await evalJs("document.querySelector('#title').value='Ashfall'; document.querySelector('#name').value='Deru';");
|
||||||
|
await sleep(200);
|
||||||
|
await shot("19-begin-post-elysium-charter3-veil0-360.png");
|
||||||
|
// switch to a one-era vault: the picker disappears
|
||||||
|
await evalJs("document.querySelector('input[name=vault][value=delvehold]').click()"); await sleep(200);
|
||||||
|
const erasForDelvehold = await evalJs("document.querySelectorAll('input[name=era]').length");
|
||||||
|
await evalJs("document.querySelector('input[name=vault][value=aetheria]').click()"); await sleep(200);
|
||||||
|
await evalJs("document.querySelector('input[name=era][value=post-elysium]').click()");
|
||||||
|
await evalJs("[...document.querySelectorAll('button')].find(b=>b.textContent==='Begin').click()"); await sleep(600);
|
||||||
|
writeFileSync(join(out, "begin-request.json"), JSON.stringify({ horizontalOverflowAt360: overflow, eraRadiosForOneEraVault: erasForDelvehold, requestSent: begun }, null, 2));
|
||||||
|
console.log(JSON.stringify({ overflow, erasForDelvehold, begun }));
|
||||||
|
ws.close(); proc.kill(); server.close();
|
||||||
22
probes/page/begin-request.json
Normal file
|
|
@ -0,0 +1,22 @@
|
||||||
|
{
|
||||||
|
"horizontalOverflowAt360": false,
|
||||||
|
"eraRadiosForOneEraVault": 0,
|
||||||
|
"requestSent": {
|
||||||
|
"key": "12b052f6-ac87-4c0a-95a7-b4b873cfe644",
|
||||||
|
"title": "Ashfall",
|
||||||
|
"name": "Deru",
|
||||||
|
"brief": null,
|
||||||
|
"vault": "aetheria",
|
||||||
|
"era": "post-elysium",
|
||||||
|
"lenses": {
|
||||||
|
"patina": 1,
|
||||||
|
"charter": 3,
|
||||||
|
"ledger": 1,
|
||||||
|
"hearth": 1,
|
||||||
|
"tangle": 1,
|
||||||
|
"veil": 0,
|
||||||
|
"ember": 1,
|
||||||
|
"numen": 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
84
probes/page/history.mjs
Normal file
|
|
@ -0,0 +1,84 @@
|
||||||
|
// Drives the history probe: api::tests::serve_the_page_for_a_browser_probe with
|
||||||
|
// GHOSTLIGHT_PROBE_MODE=long (forty scripted closed turns). Plays turns in one
|
||||||
|
// browser profile, reloads, scrolls up, then signs the same account in from a
|
||||||
|
// second, separate profile and compares what both show. 360 px phone width.
|
||||||
|
// usage: node history.mjs <base-url> <out-dir> [chrome-path]
|
||||||
|
import { spawn } from "node:child_process";
|
||||||
|
import { writeFileSync, mkdirSync, mkdtempSync } from "node:fs";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { join } from "node:path";
|
||||||
|
|
||||||
|
const [base, out, chrome = "C:/Program Files/Google/Chrome/Application/chrome.exe"] = process.argv.slice(2);
|
||||||
|
mkdirSync(out, { recursive: true });
|
||||||
|
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||||
|
|
||||||
|
async function launch(port) {
|
||||||
|
const proc = spawn(chrome, ["--headless=new", `--remote-debugging-port=${port}`, `--user-data-dir=${mkdtempSync(join(tmpdir(), "hist-"))}`, "--no-first-run", "about:blank"], { stdio: "ignore" });
|
||||||
|
let targets;
|
||||||
|
for (let i = 0; i < 50; i++) { try { targets = await (await fetch(`http://127.0.0.1:${port}/json`)).json(); break; } catch { await sleep(200); } }
|
||||||
|
const ws = new WebSocket(targets.find((t) => t.type === "page").webSocketDebuggerUrl);
|
||||||
|
await new Promise((r) => (ws.onopen = r));
|
||||||
|
let id = 0; const pending = new Map();
|
||||||
|
ws.onmessage = (m) => { const d = JSON.parse(m.data); if (d.id && pending.has(d.id)) { pending.get(d.id)(d); pending.delete(d.id); } };
|
||||||
|
const cdp = (method, params = {}) => new Promise((r) => { const n = ++id; pending.set(n, r); ws.send(JSON.stringify({ id: n, method, params })); });
|
||||||
|
const js = async (expression) => (await cdp("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true })).result.result?.value;
|
||||||
|
await cdp("Page.enable");
|
||||||
|
await cdp("Emulation.setDeviceMetricsOverride", { width: 360, height: 740, deviceScaleFactor: 2, mobile: true });
|
||||||
|
const b = {
|
||||||
|
js,
|
||||||
|
go: async (url) => { await cdp("Page.navigate", { url }); await sleep(900); },
|
||||||
|
reload: async () => { await cdp("Page.reload"); await sleep(900); },
|
||||||
|
waitFor: async (expr, ms = 20000) => { for (let t = 0; t < ms; t += 200) { if (await js(expr)) return true; await sleep(200); } throw new Error("timed out: " + expr); },
|
||||||
|
fill: (sel, v) => js(`(()=>{const e=document.querySelector(${JSON.stringify(sel)});e.value=${JSON.stringify(v)};e.dispatchEvent(new Event('input',{bubbles:true}))})()`),
|
||||||
|
clickText: (text) => js(`[...document.querySelectorAll('button')].find(x=>x.textContent.trim()===${JSON.stringify(text)}).click()`),
|
||||||
|
shot: async (name) => {
|
||||||
|
await sleep(300);
|
||||||
|
const overflow = await js("document.documentElement.scrollWidth > document.documentElement.clientWidth");
|
||||||
|
const { result } = await cdp("Page.captureScreenshot", { format: "png" });
|
||||||
|
writeFileSync(join(out, `${name}.png`), Buffer.from(result.data, "base64"));
|
||||||
|
console.log(name, "horizontal-overflow:", overflow);
|
||||||
|
},
|
||||||
|
turns: () => js("document.querySelectorAll('#log .turn').length"),
|
||||||
|
logText: () => js("document.getElementById('log').innerText"),
|
||||||
|
toBottom: () => js("window.scrollTo(0, document.documentElement.scrollHeight)"),
|
||||||
|
close: () => { ws.close(); proc.kill(); },
|
||||||
|
};
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
|
||||||
|
const A = await launch(9334);
|
||||||
|
await A.go(base + "/probe/login"); await A.waitFor("document.body.innerText.includes('Your worlds')");
|
||||||
|
await A.clickText("Begin a new world"); await A.waitFor("!!document.querySelector('#title')");
|
||||||
|
await A.fill("#title", "Ashfall"); await A.fill("#name", "Deru"); await A.clickText("Begin");
|
||||||
|
await A.waitFor("!!document.querySelector('#say')");
|
||||||
|
const N = 34;
|
||||||
|
for (let n = 0; n < N; n++) {
|
||||||
|
await A.fill("#say", `I walk on, step ${n}.`); await A.clickText("Send");
|
||||||
|
await A.waitFor(`document.getElementById('log').innerText.includes('Narration ${n}:')`);
|
||||||
|
await sleep(150);
|
||||||
|
}
|
||||||
|
await A.toBottom(); await A.shot("13-history-live-360");
|
||||||
|
await A.reload(); await A.waitFor("document.querySelectorAll('#log .turn').length > 0"); await sleep(400);
|
||||||
|
await A.toBottom();
|
||||||
|
const afterReload = await A.turns();
|
||||||
|
const newestA = await A.logText();
|
||||||
|
console.log("after reload: turns on screen", afterReload, "(first page)");
|
||||||
|
await A.shot("14-history-after-reload-360");
|
||||||
|
await A.js("window.scrollTo(0, 0)"); await A.waitFor(`document.querySelectorAll('#log .turn').length === ${N}`);
|
||||||
|
await sleep(300);
|
||||||
|
console.log("after scroll-up: turns on screen", await A.turns());
|
||||||
|
await A.shot("15-history-older-loaded-360");
|
||||||
|
const fullA = await A.logText();
|
||||||
|
|
||||||
|
const B = await launch(9335);
|
||||||
|
await B.go(base + "/probe/login"); await B.waitFor("document.querySelectorAll('#log .turn').length > 0"); await sleep(400);
|
||||||
|
await B.toBottom();
|
||||||
|
const newestB = await B.logText();
|
||||||
|
console.log("second context newest page identical to first context's after reload:", newestA === newestB);
|
||||||
|
await B.shot("16-second-context-360");
|
||||||
|
await B.js("window.scrollTo(0, 0)"); await B.waitFor(`document.querySelectorAll('#log .turn').length === ${N}`);
|
||||||
|
await sleep(300);
|
||||||
|
await B.shot("17-second-context-older-loaded-360");
|
||||||
|
const fullB = await B.logText();
|
||||||
|
console.log("full scrollback identical across contexts:", fullA === fullB, "turns:", N);
|
||||||
|
A.close(); B.close();
|
||||||
64
probes/page/shoot.mjs
Normal file
|
|
@ -0,0 +1,64 @@
|
||||||
|
// Drives the page probe (api::tests::serve_the_page_for_a_browser_probe) in headless
|
||||||
|
// Chrome over CDP and writes screenshots at 360 px and desktop width.
|
||||||
|
// usage: node shoot.mjs <base-url> <out-dir> [chrome-path]
|
||||||
|
import { spawn } from "node:child_process";
|
||||||
|
import { writeFileSync, mkdirSync, mkdtempSync } from "node:fs";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { join } from "node:path";
|
||||||
|
|
||||||
|
const [base, out, chrome = "C:/Program Files/Google/Chrome/Application/chrome.exe"] = process.argv.slice(2);
|
||||||
|
mkdirSync(out, { recursive: true });
|
||||||
|
const port = 9333;
|
||||||
|
const proc = spawn(chrome, ["--headless=new", `--remote-debugging-port=${port}`, `--user-data-dir=${mkdtempSync(join(tmpdir(), "shoot-"))}`, "--no-first-run", "about:blank"], { stdio: "ignore" });
|
||||||
|
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||||
|
let targets;
|
||||||
|
for (let i = 0; i < 50; i++) { try { targets = await (await fetch(`http://127.0.0.1:${port}/json`)).json(); break; } catch { await sleep(200); } }
|
||||||
|
const ws = new WebSocket(targets.find((t) => t.type === "page").webSocketDebuggerUrl);
|
||||||
|
await new Promise((r) => (ws.onopen = r));
|
||||||
|
let id = 0; const pending = new Map();
|
||||||
|
ws.onmessage = (m) => { const d = JSON.parse(m.data); if (d.id && pending.has(d.id)) { pending.get(d.id)(d); pending.delete(d.id); } };
|
||||||
|
const cdp = (method, params = {}) => new Promise((r) => { const n = ++id; pending.set(n, r); ws.send(JSON.stringify({ id: n, method, params })); });
|
||||||
|
const js = async (expression) => (await cdp("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true })).result.result?.value;
|
||||||
|
const widths = { phone: [360, 740], desktop: [1100, 800] };
|
||||||
|
async function shot(name) {
|
||||||
|
for (const [label, [w, h]] of Object.entries(widths)) {
|
||||||
|
await cdp("Emulation.setDeviceMetricsOverride", { width: w, height: h, deviceScaleFactor: label === "phone" ? 2 : 1, mobile: label === "phone" });
|
||||||
|
await sleep(350);
|
||||||
|
await js("document.querySelector('#say') && window.scrollTo(0, document.documentElement.scrollHeight)"); await sleep(200);
|
||||||
|
const overflow = await js("document.documentElement.scrollWidth > document.documentElement.clientWidth");
|
||||||
|
const { result } = await cdp("Page.captureScreenshot", { format: "png" });
|
||||||
|
writeFileSync(join(out, `${name}-${label}.png`), Buffer.from(result.data, "base64"));
|
||||||
|
console.log(name, label, "horizontal-overflow:", overflow);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const go = async (url) => { await cdp("Page.navigate", { url }); await sleep(900); };
|
||||||
|
const click = (sel) => js(`document.querySelector(${JSON.stringify(sel)}).click()`);
|
||||||
|
const fill = (sel, v) => js(`(()=>{const e=document.querySelector(${JSON.stringify(sel)});e.value=${JSON.stringify(v)};e.dispatchEvent(new Event('input',{bubbles:true}))})()`);
|
||||||
|
const clickText = (text) => js(`[...document.querySelectorAll('button')].find(b=>b.textContent.trim()===${JSON.stringify(text)}).click()`);
|
||||||
|
const waitFor = async (expr, ms = 20000) => { for (let t = 0; t < ms; t += 250) { if (await js(expr)) return true; await sleep(250); } return false; };
|
||||||
|
await cdp("Page.enable");
|
||||||
|
|
||||||
|
await go(base + "/"); await waitFor("!!document.querySelector('#invite')"); await shot("01-signin");
|
||||||
|
await go(base + "/#invite=abcdefgh1234"); await sleep(300);
|
||||||
|
await go(base + "/probe/login"); await waitFor("document.body.innerText.includes('Your worlds')"); await shot("02-worlds-empty");
|
||||||
|
await clickText("Begin a new world"); await waitFor("!!document.querySelector('#title')"); await shot("03-begin");
|
||||||
|
await fill("#title", "Ashfall"); await fill("#name", "Deru"); await clickText("Begin");
|
||||||
|
await waitFor("!!document.querySelector('#say')"); await shot("04-ready");
|
||||||
|
await fill("#say", "I walk up the ash road to the gate and nod to the woman at the toll hut."); await clickText("Send");
|
||||||
|
await waitFor("document.body.innerText.includes('You are late')"); await sleep(500); await shot("05-narration");
|
||||||
|
await fill("#say", "I ask what I am late for."); await clickText("Send");
|
||||||
|
await waitFor("document.body.innerText.includes('Which way')"); await sleep(500); await shot("06-question");
|
||||||
|
await fill("#say", "The lower road."); await clickText("Send");
|
||||||
|
await waitFor("document.body.innerText.includes('dogs do not bark')"); await sleep(500); await shot("07-answered-scrollback");
|
||||||
|
await fill("#say", "I draw my sword on the toll woman."); await clickText("Send");
|
||||||
|
await waitFor("document.body.innerText.includes('lost the thread')"); await sleep(500); await shot("08-fault-retry");
|
||||||
|
await clickText("Retry"); await waitFor("document.body.innerText.includes('lost the thread')"); await sleep(800); await shot("09-fault-after-retry");
|
||||||
|
// A refusal needs a dispatch the world refuses; the scripted model cannot make one cheaply, so the
|
||||||
|
// turn view the daemon would send is handed to the page's own renderer.
|
||||||
|
await js(`S.history.push({seq:999,turn_id:'probe-refusal',submission:1,text:'I reach for the toll woman.',narration:null,question:null,refusal:'The world refuses that: the toll woman is not within your reach.',fault:null,status:'refused',superseded_by:null}); render()`);
|
||||||
|
await sleep(300); await shot("10-refusal-line");
|
||||||
|
// Seeding and failed rows come from the daemon's timeline status; stub the list to see them rendered.
|
||||||
|
await js(`window.fetch=(u,o)=>String(u).endsWith('api/timelines')?Promise.resolve(new Response(JSON.stringify({timelines:[{timeline:'t1',status:'seeding',title:'Zyphos, a long first evening',current:true,createdAt:new Date().toISOString()},{timeline:'t2',status:'failed',reason:'the storyteller was unavailable',title:'Delvehold',createdAt:new Date().toISOString()},{timeline:'t3',status:'ready',parent:'t0',title:'Ashfall',createdAt:new Date().toISOString()}]}),{status:200})):Promise.reject(new Error('stub'));`);
|
||||||
|
await js("listView()"); await sleep(500); await shot("11-worlds-seeding-failed-ready");
|
||||||
|
await js("openTimeline('t1')"); await sleep(500); await shot("12-seeding-progress");
|
||||||
|
ws.close(); proc.kill();
|
||||||