Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
59b0b08b52 | ||
|
|
4cb83ad8bf | ||
|
|
95f37de18e | ||
|
|
2b25a2f766 | ||
|
|
ccf8533c6e | ||
|
|
4eac123d87 | ||
|
|
9d4f12c5dc | ||
|
|
d40fbbb3d4 | ||
|
|
c23a710a15 | ||
|
|
2a32b9aae8 | ||
|
|
44396a3cdd | ||
|
|
fcedfa0411 | ||
|
|
c78d7e58ea | ||
|
|
077bc54c0e | ||
|
|
f4c38af728 | ||
|
|
957700574b | ||
|
|
8ae66796ff | ||
|
|
2ef472f1f5 | ||
|
|
2eef1a85be | ||
|
|
f97ec46591 | ||
|
|
14320d1bdc | ||
|
|
c966ae13d7 | ||
|
|
d34a8f6ffa | ||
|
|
b85898ee58 | ||
|
|
33996e874c | ||
|
|
9c8ff5efba | ||
|
|
59c28830ab | ||
|
|
d3b0e20629 | ||
|
|
738b57bada | ||
|
|
fac31f126b | ||
|
|
85365d2aec | ||
|
|
de80f8a84a | ||
|
|
2732d38c96 | ||
|
|
ab290dc00d | ||
|
|
b423a334fc | ||
|
|
5e6303f8c4 | ||
|
|
eba61af729 | ||
|
|
342e76ce78 | ||
|
|
3d403cb1bc | ||
|
|
da62d027d2 | ||
|
|
f75e56d5c7 | ||
|
|
02757c8c59 | ||
|
|
bd14485164 | ||
|
|
c8919594c6 | ||
|
|
d846363781 | ||
|
|
0c80f39791 | ||
|
|
7c3b278aab | ||
|
|
1419b3b2c0 | ||
|
|
634d95f31d | ||
|
|
91296c0863 | ||
|
|
66d76af0b2 | ||
|
|
5fad3e75cb | ||
|
|
5075d93161 | ||
|
|
1742b24456 | ||
|
|
db4d1d2e58 | ||
|
|
07722ab396 | ||
|
|
31c36a37b7 | ||
|
|
40a28c0b69 | ||
|
|
7ff90c7cbd | ||
|
|
3f7b2a0a68 | ||
|
|
495da6b87d | ||
|
|
ded2ede38e | ||
|
|
9563694045 | ||
|
|
30a574d7aa | ||
|
|
d4d6421693 | ||
|
|
ff89da5db0 | ||
|
|
fc36079b18 | ||
|
|
5686b25816 | ||
|
|
5cb928e39f | ||
|
|
3cb7f2cb0a | ||
|
|
3e95b48d09 | ||
|
|
bce498a848 | ||
|
|
846c41dd09 | ||
|
|
98f5214010 | ||
|
|
9e6fcd6bc5 | ||
|
|
cff9e78a46 | ||
|
|
106403cf6d | ||
|
|
da967fa597 | ||
|
|
fc98772760 | ||
|
|
9e8600460e | ||
|
|
06b9520b4d | ||
|
|
6116158534 | ||
|
|
174ecfef20 | ||
|
|
c87676c4a1 | ||
|
|
09bd3f94ae | ||
|
|
964be6db44 | ||
|
|
e9612e4305 | ||
|
|
eeb6bd3f7c | ||
|
|
d0aafa974d | ||
|
|
9f22513b83 | ||
|
|
d47b241939 | ||
|
|
cdffad484a | ||
|
|
923b14b538 | ||
|
|
e8b545c518 | ||
|
|
539441196c | ||
|
|
c6df934093 | ||
|
|
ddcb777d92 | ||
|
|
ffe97ba67f | ||
|
|
b0c3a699aa | ||
|
|
d2c91cac36 | ||
|
|
47811b0928 | ||
|
|
8cbd41860d | ||
|
|
43d76f6ffe | ||
|
|
93da896890 | ||
|
|
5949034ee1 | ||
|
|
2bee6fb82a | ||
|
|
d07ddf1725 | ||
|
|
8c4bffdbba | ||
|
|
bef3245e65 | ||
|
|
7ec51de6ed | ||
|
|
2f6cc52412 | ||
|
|
373b5f35a3 | ||
|
|
56d955690b | ||
|
|
25749edb78 | ||
|
|
d3b904bd41 | ||
|
|
1fcd68f9c6 | ||
|
|
b31f1e551d | ||
|
|
9a6a1e8c73 | ||
|
|
13e8c82059 | ||
|
|
d646d59c46 | ||
|
|
94c1362b5e | ||
|
|
bc26c1116b | ||
|
|
abecfcf0f0 | ||
|
|
8d4f9ed3bb | ||
|
|
ce90413870 | ||
|
|
c9a5ce3d29 | ||
|
|
66cc6509ea | ||
|
|
2ac36ddc68 | ||
|
|
2c17cf8fa3 | ||
|
|
9a5a4f1ee5 | ||
|
|
cdf43237fc | ||
|
|
7c63ec2829 | ||
|
|
00e3467ed7 | ||
|
|
986ff92d24 | ||
|
|
1bd9578489 | ||
|
|
2d0eafd236 | ||
|
|
c23e5fd046 | ||
|
|
bc85d70f91 | ||
|
|
9684001600 | ||
|
|
91cfe7af92 | ||
|
|
1fcef6499d | ||
|
|
c58ccbe2de | ||
|
|
8d333ff817 | ||
|
|
e0c466094d | ||
|
|
4e067a073a | ||
|
|
5fa427266a | ||
|
|
c3e9e2956e | ||
|
|
419c5ed082 | ||
|
|
92fcb70aa6 | ||
|
|
0dd4787ae3 | ||
|
|
35085e6701 | ||
|
|
d3e4c3e82c | ||
|
|
f04de5e9a0 | ||
|
|
b71db89f68 | ||
|
|
51363eaccf | ||
|
|
efed95d694 | ||
|
|
1b178d2d43 | ||
|
|
47b174844a | ||
|
|
cb1f213b36 | ||
|
|
03fb33fb93 | ||
|
|
1a990a09fd | ||
|
|
f3ee217921 | ||
|
|
1e90d4a4c4 | ||
|
|
4d1e4859f4 | ||
|
|
783fd8a288 | ||
|
|
920bb3d289 | ||
|
|
b1a2d05976 | ||
|
|
48f24f94df | ||
|
|
a5ddfb9d76 | ||
|
|
7670d02a6c | ||
|
|
3fc3110edb | ||
|
|
569794fda9 | ||
|
|
588b0cca8f | ||
|
|
12f4f17ccf | ||
|
|
7327afc0c2 | ||
|
|
6575635237 | ||
|
|
6df910a925 | ||
|
|
ddab6c93bd | ||
|
|
4f53151e3d | ||
|
|
75fdd958aa | ||
|
|
c43eb54962 | ||
|
|
2b9143d303 | ||
|
|
f21b5ff1aa | ||
|
|
fec39c2010 | ||
|
|
0e9def0ebc | ||
|
|
ef11427e24 | ||
|
|
f40bbaac13 | ||
|
|
ee62fec98a | ||
|
|
eaefed1e7d | ||
|
|
56496c7108 | ||
|
|
aa56736841 | ||
|
|
f503c85484 | ||
|
|
e0344ff5af | ||
|
|
e2924bbc50 | ||
|
|
73f26a5a32 | ||
|
|
1d75f14578 | ||
|
|
ee9e18a745 | ||
|
|
771a79dde2 | ||
|
|
fca3ec1a3a | ||
|
|
e2c3511cbd | ||
|
|
824a4dea15 | ||
|
|
4741d50898 | ||
|
|
f90d408466 | ||
|
|
9ccc9fd4f2 | ||
|
|
dac9686576 | ||
|
|
d1111f4c4f | ||
|
|
9308c7d043 | ||
|
|
9747957649 | ||
|
|
fe06efcf26 | ||
|
|
b3699908f7 | ||
|
|
6d84c2b57b | ||
|
|
03b04011b7 | ||
|
|
311c4bfaed | ||
|
|
8c6a01f2ad | ||
|
|
c3f0e3789c | ||
|
|
ef7299b673 | ||
|
|
a501009210 | ||
|
|
b5b964c234 | ||
|
|
2dabb85009 | ||
|
|
706d0c3792 | ||
|
|
5f2e629c32 | ||
|
|
d1883e9973 | ||
|
|
92275cbe7c | ||
|
|
2a888da955 | ||
|
|
5cf005eb2c | ||
|
|
b5dc76dd75 | ||
|
|
61042670d1 | ||
|
|
cb1be44f92 | ||
|
|
9bf7932573 | ||
|
|
db12c26b31 | ||
|
|
2b495e1f33 | ||
|
|
adb8cbff2b | ||
|
|
158e8f9f3d | ||
|
|
278033b90e | ||
|
|
be7d9eec75 | ||
|
|
5277973afb | ||
|
|
06a8373fbd | ||
|
|
06e30dc921 | ||
|
|
097bf02f1e | ||
|
|
fc3f9fd668 | ||
|
|
cef6436971 | ||
|
|
2daa80e159 | ||
|
|
4eff650755 | ||
|
|
e854cf3671 | ||
|
|
8f6b552e7a | ||
|
|
9afbdc879e | ||
|
|
42e71d89d5 | ||
|
|
677eb1b3a8 | ||
|
|
3eb59068c7 | ||
|
|
b5edc05b1f | ||
|
|
84b8e3d6d5 | ||
|
|
c3e16a57c2 | ||
|
|
f167683e8d | ||
|
|
308169ac51 | ||
|
|
4126c83eff | ||
|
|
ecff1ac25b | ||
|
|
e651d9e863 | ||
|
|
2c5eb95da3 | ||
|
|
ee174c68ce | ||
|
|
1afd942be3 | ||
|
|
c750e21c2d | ||
|
|
e085286126 | ||
|
|
525666f79b | ||
|
|
b8465e50d3 | ||
|
|
8c9b88b519 | ||
|
|
327cbe3c5e | ||
|
|
bd8dc756d9 | ||
|
|
fbd8bdb8ca | ||
|
|
e5ae6fe7af | ||
|
|
c11e8a16ba | ||
|
|
2e9905f42f | ||
|
|
f74dec6675 | ||
|
|
e28bf3fd55 | ||
|
|
b2447e4f99 | ||
|
|
8d263bb60e | ||
|
|
b0f57a009b | ||
|
|
74f3b7011f | ||
|
|
b3d5843e71 | ||
|
|
aef08ce3a6 | ||
|
|
f178684391 | ||
|
|
831f10458e | ||
|
|
0d28508180 | ||
|
|
dd80e29484 | ||
|
|
7262e72a0d | ||
|
|
8912dde49f | ||
|
|
90c5e3b337 | ||
|
|
1645f4a972 | ||
|
|
f89be06a33 | ||
|
|
efa7d5cff2 | ||
|
|
367e2eb50f | ||
|
|
9f2904ffb8 | ||
|
|
ea8538761b | ||
|
|
4f92840fe7 | ||
|
|
8ca2c5556c | ||
|
|
82a0c1b4f0 | ||
|
|
5b6796d1e6 | ||
|
|
0c0e1c73db | ||
|
|
c47a0785c9 | ||
|
|
d79a96ede4 | ||
|
|
82a500eedb | ||
|
|
b64b61c345 | ||
|
|
189d1d3c2b | ||
|
|
97e39f48fd | ||
|
|
3ee4ab8e88 | ||
|
|
29efabe4d8 | ||
|
|
5a876bf615 | ||
|
|
6db5d0873e | ||
|
|
1e6da32ad3 | ||
|
|
f0adcc61c5 | ||
|
|
e1c2632f03 | ||
|
|
26f533e8f4 | ||
|
|
57b16df286 | ||
|
|
72a98d8468 | ||
|
|
2b6e8c7826 | ||
|
|
1b31bfc399 | ||
|
|
af7e544830 | ||
|
|
c4bc865573 |
130 changed files with 44898 additions and 23825 deletions
5
.gitignore
vendored
5
.gitignore
vendored
|
|
@ -1,6 +1,4 @@
|
||||||
node_modules/
|
node_modules/
|
||||||
web/dist/
|
|
||||||
sidecar/claude-sdk/dist/
|
|
||||||
target/
|
target/
|
||||||
|
|
||||||
# Disposable local scaffolding. These accumulated to ~87MB of untracked debris
|
# Disposable local scaffolding. These accumulated to ~87MB of untracked debris
|
||||||
|
|
@ -13,3 +11,6 @@ target/
|
||||||
|
|
||||||
# Claude Code agent worktrees (Hands/Soul isolation); never source
|
# Claude Code agent worktrees (Hands/Soul isolation); never source
|
||||||
.claude/worktrees/
|
.claude/worktrees/
|
||||||
|
|
||||||
|
# Captured probe screenshots (scripts and fixtures under probes/page/ stay tracked)
|
||||||
|
probes/page/*.png
|
||||||
|
|
|
||||||
3
.gitmodules
vendored
3
.gitmodules
vendored
|
|
@ -1,3 +0,0 @@
|
||||||
[submodule "vendor/eve"]
|
|
||||||
path = vendor/eve
|
|
||||||
url = https://github.com/GameCult/Eve.git
|
|
||||||
36
AGENTS.md
36
AGENTS.md
|
|
@ -5,14 +5,17 @@
|
||||||
Ghostlight is a Rust world kernel and the play daemon built on it. Models
|
Ghostlight is a Rust world kernel and the play daemon built on it. Models
|
||||||
propose; the kernel admits or refuses. The same kernel is meant to run the
|
propose; the kernel admits or refuses. The same kernel is meant to run the
|
||||||
simulation behind Aetheria's public story, a persistent cast and storylets, as
|
simulation behind Aetheria's public story, a persistent cast and storylets, as
|
||||||
well as Ghostlight Dungeon, the single-player DM-led client. `README.md` says
|
well as Ghostlight Dungeon (`crates/ghostlight-dungeon` and
|
||||||
what exists today and what does not.
|
`deployment/idunn/recipe.toml`, live on `main` for the Dungeon playtest; the
|
||||||
|
earlier Eve surface is at tag `parked/ghostlight-eve-surface`). `README.md`
|
||||||
|
says what exists today and what does not.
|
||||||
|
|
||||||
## Where State Lives
|
## Where State Lives
|
||||||
|
|
||||||
- Campaign state (targets, rulings, cut specs, reports, verdicts, findings,
|
- Campaign state (targets, rulings, cut specs, reports, verdicts, findings,
|
||||||
follow-ups) lives in the Eureka mind, not in this repo. The current campaign
|
follow-ups) lives in the Eureka mind, not in this repo. The current campaign
|
||||||
is `ghostlight-verse`; query it through the `eureka-state` tools.
|
is `ghostlight-verse`; query it through the `huginn` CLI
|
||||||
|
(`EUREKA_INSTANCE=weksa`, `HUGINN_ENDPOINT=rudp://10.77.0.1:17877`).
|
||||||
- `notes/ghostlight-verse-target.md` and `notes/ghostlight-verse-map.md` are the
|
- `notes/ghostlight-verse-target.md` and `notes/ghostlight-verse-map.md` are the
|
||||||
campaign's prose target and map. Read the map for probed body facts.
|
campaign's prose target and map. Read the map for probed body facts.
|
||||||
- This repo has no state directory, no state CLI, and no evidence ledger. Do not
|
- This repo has no state directory, no state CLI, and no evidence ledger. Do not
|
||||||
|
|
@ -55,28 +58,23 @@ what exists today and what does not.
|
||||||
- Kernel: `crates/ghostlight/src/`. Its vocabulary and current mechanism:
|
- Kernel: `crates/ghostlight/src/`. Its vocabulary and current mechanism:
|
||||||
`docs/architecture/ghostlight-world-ontology.md`. The consumer contract:
|
`docs/architecture/ghostlight-world-ontology.md`. The consumer contract:
|
||||||
`docs/architecture/ghostlight-world-consumer-api.md`.
|
`docs/architecture/ghostlight-world-consumer-api.md`.
|
||||||
- Dungeon daemon: `crates/ghostlight-dungeon/src/` (`runtime.rs` for routes and
|
- Dungeon daemon and Idunn recipe: `crates/ghostlight-dungeon/` and
|
||||||
commands, `play.rs` for the play table, `eve.rs` for the surface).
|
`deployment/idunn/recipe.toml` (the earlier Eve surface is at tag
|
||||||
Interface authority: `docs/architecture/ghostlight-eve-native-interface.md`.
|
`parked/ghostlight-eve-surface`).
|
||||||
- Persona membrane: `crates/ghostlight-persona-projection/src/lib.rs`.
|
- Persona membrane: `crates/ghostlight-persona-projection/src/lib.rs`.
|
||||||
- Browser host: `web/`. Claude SDK sidecar: `sidecar/claude-sdk/`.
|
- Architecture rationale (earlier Dungeon / parked Eve surface design record):
|
||||||
- Architecture rationale: `docs/architecture/ghostlight-dungeon-mvp.md`.
|
`docs/architecture/ghostlight-dungeon-mvp.md`.
|
||||||
`notes/ghostlight-implementation-plan.md` is the historical plan of the 2026-09
|
`notes/ghostlight-implementation-plan.md` is the historical plan of the 2026-09
|
||||||
rebuild, not the current plan.
|
rebuild, not the current plan.
|
||||||
|
|
||||||
## Build, Verify, Deploy
|
## Build, Verify, Deploy
|
||||||
|
|
||||||
Ghostlight Dungeon ships to Linux on Yggdrasil. Idunn freezes an exact commit,
|
`crates/ghostlight-dungeon` deploys to Yggdrasil from `deployment/idunn/recipe.toml`
|
||||||
runs the locked native Linux tests, builds the daemon and web projection in
|
for the Dungeon playtest (brake release admitted in
|
||||||
pinned containers, and seals the release. The steps are
|
`ghostlight-verse:ruling:ghostlight-brake-release-granted`). Kernel, verse, and
|
||||||
`deployment/idunn/recipe.toml`; the owning runbook is
|
Dungeon tests run on Linux on Yggdrasil (the `ygg-verify` stopgap), not on the
|
||||||
`gamecult-ops/runbooks/ghostlight-dungeon-yggdrasil.md`.
|
workstation; a Windows compile is not evidence about Linux, so say which host you
|
||||||
|
used.
|
||||||
You are probably reading this on a Windows workstation. That is where the shell
|
|
||||||
is, not where the artifact runs. A Windows compile is not evidence about the
|
|
||||||
Linux release; build for the target, or let the deploy path's builder do it, and
|
|
||||||
say which one you used. Heavy builds and test runs go to Yggdrasil, not the
|
|
||||||
workstation. Deploy only through Idunn (`idunn up ghostlight`).
|
|
||||||
|
|
||||||
For infrastructure, SSH, Idunn, Odin, or Heimdall work, consult
|
For infrastructure, SSH, Idunn, Odin, or Heimdall work, consult
|
||||||
`F:\Projects\gamecult-ops` before acting.
|
`F:\Projects\gamecult-ops` before acting.
|
||||||
|
|
|
||||||
339
Cargo.lock
generated
339
Cargo.lock
generated
|
|
@ -61,6 +61,15 @@ version = "1.0.104"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
|
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "ar_archive_writer"
|
||||||
|
version = "0.5.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "523e5e187fff36fcb8d1d19ccf0ca4ca43ec3d158316057f66dc6f72716bc5ec"
|
||||||
|
dependencies = [
|
||||||
|
"object",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "async-stream"
|
name = "async-stream"
|
||||||
version = "0.3.6"
|
version = "0.3.6"
|
||||||
|
|
@ -176,12 +185,6 @@ version = "0.22.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "base64"
|
|
||||||
version = "0.23.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "base64ct"
|
name = "base64ct"
|
||||||
version = "1.8.3"
|
version = "1.8.3"
|
||||||
|
|
@ -272,22 +275,6 @@ dependencies = [
|
||||||
"inout",
|
"inout",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "codex-connector"
|
|
||||||
version = "0.1.0"
|
|
||||||
source = "git+https://github.com/GameCult/CodexConnector.git?rev=68fe94b9475823de92ed766a97ea962d48723708#68fe94b9475823de92ed766a97ea962d48723708"
|
|
||||||
dependencies = [
|
|
||||||
"aes-gcm",
|
|
||||||
"base64 0.23.1",
|
|
||||||
"rand_core 0.6.4",
|
|
||||||
"rmp-serde",
|
|
||||||
"serde",
|
|
||||||
"serde_json",
|
|
||||||
"sha2",
|
|
||||||
"thiserror",
|
|
||||||
"zeroize",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "const-oid"
|
name = "const-oid"
|
||||||
version = "0.9.6"
|
version = "0.9.6"
|
||||||
|
|
@ -345,7 +332,7 @@ source = "git+https://github.com/GameCult/CultLib.git?rev=85f7024a35ea42cf9f0a01
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"chrono",
|
"chrono",
|
||||||
"cultcache-rs-derive",
|
"cultcache-rs-derive 0.1.0",
|
||||||
"fs2",
|
"fs2",
|
||||||
"redb",
|
"redb",
|
||||||
"rmp-serde",
|
"rmp-serde",
|
||||||
|
|
@ -356,6 +343,26 @@ dependencies = [
|
||||||
"windows-sys 0.59.0",
|
"windows-sys 0.59.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "cultcache-rs"
|
||||||
|
version = "0.3.1"
|
||||||
|
source = "git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23#a4eae9056152335662f1115f97bf35fb00ab6d23"
|
||||||
|
dependencies = [
|
||||||
|
"anyhow",
|
||||||
|
"chrono",
|
||||||
|
"cultcache-rs-derive 0.2.0",
|
||||||
|
"fs2",
|
||||||
|
"redb",
|
||||||
|
"rmp-serde",
|
||||||
|
"serde",
|
||||||
|
"serde_bytes",
|
||||||
|
"serde_json",
|
||||||
|
"serde_stacker",
|
||||||
|
"stacker",
|
||||||
|
"uuid",
|
||||||
|
"windows-sys 0.59.0",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cultcache-rs-derive"
|
name = "cultcache-rs-derive"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
|
|
@ -366,14 +373,24 @@ dependencies = [
|
||||||
"syn 2.0.119",
|
"syn 2.0.119",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "cultcache-rs-derive"
|
||||||
|
version = "0.2.0"
|
||||||
|
source = "git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23#a4eae9056152335662f1115f97bf35fb00ab6d23"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn 2.0.119",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cultmesh-rs"
|
name = "cultmesh-rs"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
source = "git+https://github.com/GameCult/CultLib.git?rev=85f7024a35ea42cf9f0a0199a064526427150191#85f7024a35ea42cf9f0a0199a064526427150191"
|
source = "git+https://github.com/GameCult/CultLib.git?rev=85f7024a35ea42cf9f0a0199a064526427150191#85f7024a35ea42cf9f0a0199a064526427150191"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"cultcache-rs",
|
"cultcache-rs 0.1.0",
|
||||||
"cultnet-rs",
|
"cultnet-rs 0.1.0",
|
||||||
"serde",
|
"serde",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
@ -384,9 +401,34 @@ source = "git+https://github.com/GameCult/CultLib.git?rev=85f7024a35ea42cf9f0a01
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"aes-gcm",
|
"aes-gcm",
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"base64 0.22.1",
|
"base64",
|
||||||
"chrono",
|
"chrono",
|
||||||
"cultcache-rs",
|
"cultcache-rs 0.1.0",
|
||||||
|
"ed25519-dalek",
|
||||||
|
"hmac",
|
||||||
|
"rand 0.9.5",
|
||||||
|
"rmp-serde",
|
||||||
|
"rmpv",
|
||||||
|
"serde",
|
||||||
|
"serde_bytes",
|
||||||
|
"serde_json",
|
||||||
|
"sha2",
|
||||||
|
"socket2 0.5.10",
|
||||||
|
"uuid",
|
||||||
|
"windows-sys 0.61.2",
|
||||||
|
"zeroize",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "cultnet-rs"
|
||||||
|
version = "0.2.0"
|
||||||
|
source = "git+https://github.com/GameCult/CultLib.git?rev=a4eae9056152335662f1115f97bf35fb00ab6d23#a4eae9056152335662f1115f97bf35fb00ab6d23"
|
||||||
|
dependencies = [
|
||||||
|
"aes-gcm",
|
||||||
|
"anyhow",
|
||||||
|
"base64",
|
||||||
|
"chrono",
|
||||||
|
"cultcache-rs 0.3.1",
|
||||||
"ed25519-dalek",
|
"ed25519-dalek",
|
||||||
"hmac",
|
"hmac",
|
||||||
"rand 0.9.5",
|
"rand 0.9.5",
|
||||||
|
|
@ -441,9 +483,9 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "deranged"
|
name = "deranged"
|
||||||
version = "0.5.8"
|
version = "0.5.9"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
|
checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "digest"
|
name = "digest"
|
||||||
|
|
@ -467,6 +509,12 @@ dependencies = [
|
||||||
"syn 3.0.3",
|
"syn 3.0.3",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "dyn-clone"
|
||||||
|
version = "1.0.20"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ed25519"
|
name = "ed25519"
|
||||||
version = "2.2.3"
|
version = "2.2.3"
|
||||||
|
|
@ -663,11 +711,12 @@ version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"async-trait",
|
"async-trait",
|
||||||
"chrono",
|
"chrono",
|
||||||
"codex-connector",
|
"cultcache-rs 0.1.0",
|
||||||
"cultcache-rs",
|
|
||||||
"ghostlight-persona-projection",
|
"ghostlight-persona-projection",
|
||||||
|
"model-connector",
|
||||||
"reqwest",
|
"reqwest",
|
||||||
"rmp-serde",
|
"rmp-serde",
|
||||||
|
"rmpv",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_bytes",
|
"serde_bytes",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
|
|
@ -676,6 +725,8 @@ dependencies = [
|
||||||
"thiserror",
|
"thiserror",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tracing",
|
"tracing",
|
||||||
|
"unicode-normalization",
|
||||||
|
"unicode-properties",
|
||||||
"uuid",
|
"uuid",
|
||||||
"zeroize",
|
"zeroize",
|
||||||
]
|
]
|
||||||
|
|
@ -689,29 +740,27 @@ dependencies = [
|
||||||
"async-stream",
|
"async-stream",
|
||||||
"async-trait",
|
"async-trait",
|
||||||
"axum",
|
"axum",
|
||||||
"base64 0.22.1",
|
"base64",
|
||||||
"chrono",
|
"chrono",
|
||||||
"codex-connector",
|
"cultcache-rs 0.1.0",
|
||||||
"cultcache-rs",
|
|
||||||
"cultmesh-rs",
|
"cultmesh-rs",
|
||||||
"cultnet-rs",
|
"cultnet-rs 0.1.0",
|
||||||
"ghostlight",
|
"ghostlight",
|
||||||
"ghostlight-persona-projection",
|
"ghostlight-persona-projection",
|
||||||
"hmac",
|
"hmac",
|
||||||
"jsonwebtoken",
|
"jsonwebtoken",
|
||||||
"libc",
|
"libc",
|
||||||
|
"model-connector",
|
||||||
"rand 0.9.5",
|
"rand 0.9.5",
|
||||||
"reqwest",
|
"reqwest",
|
||||||
"rmp-serde",
|
"rmp-serde",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_bytes",
|
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"sha2",
|
"sha2",
|
||||||
"tempfile",
|
"tempfile",
|
||||||
"thiserror",
|
"thiserror",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tower",
|
"tower",
|
||||||
"tower-http",
|
|
||||||
"tracing",
|
"tracing",
|
||||||
"tracing-subscriber",
|
"tracing-subscriber",
|
||||||
"uuid",
|
"uuid",
|
||||||
|
|
@ -727,6 +776,18 @@ dependencies = [
|
||||||
"unicode-segmentation",
|
"unicode-segmentation",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "ghostlight-verse"
|
||||||
|
version = "0.1.0"
|
||||||
|
dependencies = [
|
||||||
|
"anyhow",
|
||||||
|
"chrono",
|
||||||
|
"ghostlight",
|
||||||
|
"serde_json",
|
||||||
|
"tempfile",
|
||||||
|
"tokio",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "hmac"
|
name = "hmac"
|
||||||
version = "0.12.1"
|
version = "0.12.1"
|
||||||
|
|
@ -769,12 +830,6 @@ dependencies = [
|
||||||
"pin-project-lite",
|
"pin-project-lite",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "http-range-header"
|
|
||||||
version = "0.4.2"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "9171a2ea8a68358193d15dd5d70c1c10a2afc3e7e4c5bc92bc9f025cebd7359c"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "httparse"
|
name = "httparse"
|
||||||
version = "1.10.1"
|
version = "1.10.1"
|
||||||
|
|
@ -830,7 +885,7 @@ version = "0.1.20"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"
|
checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"base64 0.22.1",
|
"base64",
|
||||||
"bytes",
|
"bytes",
|
||||||
"futures-channel",
|
"futures-channel",
|
||||||
"futures-util",
|
"futures-util",
|
||||||
|
|
@ -1013,7 +1068,7 @@ version = "9.3.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "5a87cc7a48537badeae96744432de36f4be2b4a34a05a5ef32e9dd8a1c169dde"
|
checksum = "5a87cc7a48537badeae96744432de36f4be2b4a34a05a5ef32e9dd8a1c169dde"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"base64 0.22.1",
|
"base64",
|
||||||
"js-sys",
|
"js-sys",
|
||||||
"pem",
|
"pem",
|
||||||
"ring",
|
"ring",
|
||||||
|
|
@ -1024,9 +1079,9 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "lazy_static"
|
name = "lazy_static"
|
||||||
version = "1.5.0"
|
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 = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
|
checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "libc"
|
name = "libc"
|
||||||
|
|
@ -1090,19 +1145,9 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "mime"
|
name = "mime"
|
||||||
version = "0.3.17"
|
version = "0.3.18"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
|
checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "mime_guess"
|
|
||||||
version = "2.0.5"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e"
|
|
||||||
dependencies = [
|
|
||||||
"mime",
|
|
||||||
"unicase",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "mio"
|
name = "mio"
|
||||||
|
|
@ -1115,6 +1160,26 @@ dependencies = [
|
||||||
"windows-sys 0.61.2",
|
"windows-sys 0.61.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "model-connector"
|
||||||
|
version = "0.1.0"
|
||||||
|
source = "git+https://eureka.gamecult.org/forge/GameCult/ModelConnector.git?rev=edf2f8e03cbb61df385b9b145b46f676ce3b70d5#edf2f8e03cbb61df385b9b145b46f676ce3b70d5"
|
||||||
|
dependencies = [
|
||||||
|
"aes-gcm",
|
||||||
|
"base64",
|
||||||
|
"cultnet-rs 0.2.0",
|
||||||
|
"rand_core 0.6.4",
|
||||||
|
"rmp-serde",
|
||||||
|
"rmpv",
|
||||||
|
"schemars",
|
||||||
|
"serde",
|
||||||
|
"serde_bytes",
|
||||||
|
"serde_json",
|
||||||
|
"sha2",
|
||||||
|
"thiserror",
|
||||||
|
"zeroize",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "nu-ansi-term"
|
name = "nu-ansi-term"
|
||||||
version = "0.50.3"
|
version = "0.50.3"
|
||||||
|
|
@ -1158,6 +1223,15 @@ dependencies = [
|
||||||
"autocfg",
|
"autocfg",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "object"
|
||||||
|
version = "0.39.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b"
|
||||||
|
dependencies = [
|
||||||
|
"memchr",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "once_cell"
|
name = "once_cell"
|
||||||
version = "1.21.4"
|
version = "1.21.4"
|
||||||
|
|
@ -1199,7 +1273,7 @@ version = "3.0.6"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be"
|
checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"base64 0.22.1",
|
"base64",
|
||||||
"serde_core",
|
"serde_core",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
@ -1248,9 +1322,9 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "powerfmt"
|
name = "powerfmt"
|
||||||
version = "0.2.0"
|
version = "0.2.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
|
checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ppv-lite86"
|
name = "ppv-lite86"
|
||||||
|
|
@ -1270,6 +1344,16 @@ dependencies = [
|
||||||
"unicode-ident",
|
"unicode-ident",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "psm"
|
||||||
|
version = "0.1.32"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622"
|
||||||
|
dependencies = [
|
||||||
|
"ar_archive_writer",
|
||||||
|
"cc",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "quinn"
|
name = "quinn"
|
||||||
version = "0.11.11"
|
version = "0.11.11"
|
||||||
|
|
@ -1430,10 +1514,30 @@ dependencies = [
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "regex-automata"
|
name = "ref-cast"
|
||||||
version = "0.4.18"
|
version = "1.0.27"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
|
checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3"
|
||||||
|
dependencies = [
|
||||||
|
"ref-cast-impl",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "ref-cast-impl"
|
||||||
|
version = "1.0.27"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn 3.0.3",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "regex-automata"
|
||||||
|
version = "0.4.19"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"aho-corasick",
|
"aho-corasick",
|
||||||
"memchr",
|
"memchr",
|
||||||
|
|
@ -1442,9 +1546,9 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "regex-syntax"
|
name = "regex-syntax"
|
||||||
version = "0.8.11"
|
version = "0.8.12"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
|
checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "reqwest"
|
name = "reqwest"
|
||||||
|
|
@ -1452,7 +1556,7 @@ version = "0.12.28"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
|
checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"base64 0.22.1",
|
"base64",
|
||||||
"bytes",
|
"bytes",
|
||||||
"futures-core",
|
"futures-core",
|
||||||
"futures-util",
|
"futures-util",
|
||||||
|
|
@ -1606,6 +1710,31 @@ version = "1.0.23"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
|
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "schemars"
|
||||||
|
version = "1.2.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e"
|
||||||
|
dependencies = [
|
||||||
|
"dyn-clone",
|
||||||
|
"ref-cast",
|
||||||
|
"schemars_derive",
|
||||||
|
"serde",
|
||||||
|
"serde_json",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "schemars_derive"
|
||||||
|
version = "1.2.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e1c3a92094fa7d61aa124645844facb6b554dfc797136d0f5fd1f890e2bffc69"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"serde_derive_internals",
|
||||||
|
"syn 3.0.3",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "scopeguard"
|
name = "scopeguard"
|
||||||
version = "1.2.0"
|
version = "1.2.0"
|
||||||
|
|
@ -1658,6 +1787,17 @@ dependencies = [
|
||||||
"syn 3.0.3",
|
"syn 3.0.3",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "serde_derive_internals"
|
||||||
|
version = "0.30.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn 3.0.3",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "serde_json"
|
name = "serde_json"
|
||||||
version = "1.0.151"
|
version = "1.0.151"
|
||||||
|
|
@ -1682,6 +1822,17 @@ dependencies = [
|
||||||
"serde_core",
|
"serde_core",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "serde_stacker"
|
||||||
|
version = "0.1.14"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d4936375d50c4be7eff22293a9344f8e46f323ed2b3c243e52f89138d9bb0f4a"
|
||||||
|
dependencies = [
|
||||||
|
"serde",
|
||||||
|
"serde_core",
|
||||||
|
"stacker",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "serde_urlencoded"
|
name = "serde_urlencoded"
|
||||||
version = "0.7.1"
|
version = "0.7.1"
|
||||||
|
|
@ -1799,6 +1950,19 @@ version = "1.2.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
|
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "stacker"
|
||||||
|
version = "0.1.25"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967"
|
||||||
|
dependencies = [
|
||||||
|
"cc",
|
||||||
|
"cfg-if",
|
||||||
|
"libc",
|
||||||
|
"psm",
|
||||||
|
"windows-sys 0.61.2",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "subtle"
|
name = "subtle"
|
||||||
version = "2.6.1"
|
version = "2.6.1"
|
||||||
|
|
@ -2019,23 +2183,13 @@ checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bitflags",
|
"bitflags",
|
||||||
"bytes",
|
"bytes",
|
||||||
"futures-core",
|
|
||||||
"futures-util",
|
"futures-util",
|
||||||
"http",
|
"http",
|
||||||
"http-body",
|
"http-body",
|
||||||
"http-body-util",
|
|
||||||
"http-range-header",
|
|
||||||
"httpdate",
|
|
||||||
"mime",
|
|
||||||
"mime_guess",
|
|
||||||
"percent-encoding",
|
|
||||||
"pin-project-lite",
|
"pin-project-lite",
|
||||||
"tokio",
|
|
||||||
"tokio-util",
|
|
||||||
"tower",
|
"tower",
|
||||||
"tower-layer",
|
"tower-layer",
|
||||||
"tower-service",
|
"tower-service",
|
||||||
"tracing",
|
|
||||||
"url",
|
"url",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
@ -2125,18 +2279,27 @@ version = "1.20.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
|
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "unicase"
|
|
||||||
version = "2.9.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "unicode-ident"
|
name = "unicode-ident"
|
||||||
version = "1.0.24"
|
version = "1.0.24"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "unicode-normalization"
|
||||||
|
version = "0.1.25"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8"
|
||||||
|
dependencies = [
|
||||||
|
"tinyvec",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "unicode-properties"
|
||||||
|
version = "0.1.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "unicode-segmentation"
|
name = "unicode-segmentation"
|
||||||
version = "1.13.3"
|
version = "1.13.3"
|
||||||
|
|
@ -2531,18 +2694,18 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "zerocopy"
|
name = "zerocopy"
|
||||||
version = "0.8.56"
|
version = "0.8.66"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "556764e583adb45a9f8d413c2a147fa7e8d821e48e12b14fd560b607998b75eb"
|
checksum = "cba8a86aee14fc8cc6c208af60854b3d4ab7185a9a369a12c648faa2716ff42a"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"zerocopy-derive",
|
"zerocopy-derive",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "zerocopy-derive"
|
name = "zerocopy-derive"
|
||||||
version = "0.8.56"
|
version = "0.8.66"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "f2ab42fc20575779bd240faa45f94a74256f755c0fa9e89f0ede20d91d0cdfc1"
|
checksum = "f89bca3b96ceb3cfcb4572790402f977442270d252b9a8504ebc258760c55f94"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@ members = [
|
||||||
"crates/ghostlight",
|
"crates/ghostlight",
|
||||||
"crates/ghostlight-dungeon",
|
"crates/ghostlight-dungeon",
|
||||||
"crates/ghostlight-persona-projection",
|
"crates/ghostlight-persona-projection",
|
||||||
|
"crates/ghostlight-verse",
|
||||||
]
|
]
|
||||||
resolver = "2"
|
resolver = "2"
|
||||||
|
|
||||||
|
|
@ -19,7 +20,7 @@ async-stream = "0.3"
|
||||||
axum = { version = "0.8", features = ["macros"] }
|
axum = { version = "0.8", features = ["macros"] }
|
||||||
chrono = { version = "0.4", features = ["serde"] }
|
chrono = { version = "0.4", features = ["serde"] }
|
||||||
base64 = "0.22"
|
base64 = "0.22"
|
||||||
codex-connector = { git = "https://github.com/GameCult/CodexConnector.git", rev = "68fe94b9475823de92ed766a97ea962d48723708" }
|
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" }
|
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" }
|
cultmesh-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "85f7024a35ea42cf9f0a0199a064526427150191", package = "cultmesh-rs" }
|
||||||
|
|
@ -33,7 +34,6 @@ serde_json = "1"
|
||||||
sha2 = "0.10"
|
sha2 = "0.10"
|
||||||
thiserror = "2"
|
thiserror = "2"
|
||||||
tokio = { version = "1", features = ["full"] }
|
tokio = { version = "1", features = ["full"] }
|
||||||
tower-http = { version = "0.6", features = ["fs", "trace"] }
|
|
||||||
tracing = "0.1"
|
tracing = "0.1"
|
||||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||||
unicode-segmentation = "1"
|
unicode-segmentation = "1"
|
||||||
|
|
|
||||||
225
README.md
225
README.md
|
|
@ -1,148 +1,123 @@
|
||||||
# Ghostlight
|
# Ghostlight
|
||||||
|
|
||||||
Ghostlight is a Rust library that keeps a simulated world honest, and a play
|
**Ghostlight is a world kernel: typed world state that a language model can
|
||||||
daemon built on it. A language model proposes; the library's kernel checks each
|
propose changes to and can never write.** The valuable part is
|
||||||
proposal against typed world state and admits or refuses it. Places, people,
|
`crates/ghostlight`. The live Dungeon playtest daemon (`crates/ghostlight-dungeon`,
|
||||||
knowledge, commitments, and time live in the kernel's journal, not in a model's
|
below) is one client of it; the earlier Eve surface is parked.
|
||||||
context window, so they survive restarts and long stories.
|
|
||||||
|
|
||||||
## What is here
|
**The thesis.** World state is typed documents. Every change to it, and every
|
||||||
|
narrative dependency on it, is an operation in a closed, predefined algebra.
|
||||||
|
Models propose operations; the kernel checks each against the state (references,
|
||||||
|
preconditions, authority, conservation, who knows what) and admits it or refuses
|
||||||
|
it with the complete list of mismatches. Narration describes only what was
|
||||||
|
committed. A model-as-game-master holds the world in a context window and
|
||||||
|
drifts; here the world is a digest-chained journal that survives restarts and
|
||||||
|
cannot be talked into contradicting itself.
|
||||||
|
|
||||||
| Part | Path | What it is |
|
**Use it as a structured state backend.** Do not judge it by the Dungeon playtest's
|
||||||
|---|---|---|
|
or the earlier parked Eve surface's prose. The kernel is a library; prose comes
|
||||||
| World kernel | `crates/ghostlight/` | The sealed `ghostlight` library: world state, the closed operation set and reducer, the CultCache journal, the mailbox that is its only door, controllers, elaboration, lenses, the consumer ingress, and the inference ports. |
|
from whichever model you plug into its ports.
|
||||||
| Persona projection | `crates/ghostlight-persona-projection/` | The membrane between structured state and a prose-only Persona: projection, Persona turn receipts, and the controller descriptors the kernel consumes. |
|
|
||||||
| Dungeon | `crates/ghostlight-dungeon/` | The `ghostlight-dungeon` daemon: single-player, DM-led play over one world. HTTP and Eve routes, Heimdall sign-in, app sessions, the play table, CultMesh publication, and Idunn health. |
|
|
||||||
| Browser | `web/` | A thin Eve browser host and the Heimdall access adapter. It renders the server's surface and owns no product state. |
|
|
||||||
| Claude SDK sidecar | `sidecar/claude-sdk/` | A Node process that serves `claude`-prefixed models to the kernel through the Claude Agent SDK. It is a stopgap for a direct Messages API port. |
|
|
||||||
| Deploy recipe | `deployment/idunn/recipe.toml` | The steps Idunn runs to test, build, and seal a release. |
|
|
||||||
| Eve | `vendor/eve/` | A git submodule (`.gitmodules`) supplying the Eve browser lowering and contracts. |
|
|
||||||
|
|
||||||
## How it works
|
- `crates/ghostlight`: the sealed library. A consumer gets create/open
|
||||||
|
(`WorldMailbox::open`, `create`), immutable snapshots (`snapshot`), command
|
||||||
|
submission through role-scoped ports (`PlayPort`, `ConsumerPort`,
|
||||||
|
`ControllerPort`, `SeedPort`), typed receipts, and the runner and inference-port
|
||||||
|
entry points (`ControllerRunner`, `ElaborationRunner`, `SeedRunner`,
|
||||||
|
`InferencePort`). Mutable state, ID issuers, the reducer and the journal
|
||||||
|
writer are not public. `compile_fail` doc-tests in `crates/ghostlight/src/lib.rs`
|
||||||
|
and `crates/ghostlight/tests/external_admission.rs` prove the seal.
|
||||||
|
- `docs/architecture/ghostlight-world-ontology.md`: the vocabulary (subjects,
|
||||||
|
places, routes, holdings, knowledge, commitments, pressures), the operation
|
||||||
|
algebra, and what the reducer checks.
|
||||||
|
- `docs/architecture/ghostlight-world-consumer-api.md`: the contract for a
|
||||||
|
program that reads a world and proposes changes to the characters it controls
|
||||||
|
(`POST /cultnet/world-patch`; no process on main serves that door, a host serves
|
||||||
|
`ghostlight::admit_document`).
|
||||||
|
|
||||||
- The kernel is sealed. A consumer reaches it through create/open, immutable
|
Start with those two documents, then `cargo doc -p ghostlight --open`.
|
||||||
snapshots, command submission, typed receipts, and the runner and port entry
|
|
||||||
points. There is no public mutable state, ID issuer, reducer, or journal
|
**Populate the algebra first.** The kernel owns the component operations; a world owns its
|
||||||
writer, and the crate declares no cargo features. The seal is proven by
|
affordance catalog, the verbs its actors can attempt. A fresh world knows one: the built-in
|
||||||
`compile_fail` doc-tests in `crates/ghostlight/src/lib.rs` and by
|
Speak, which records an utterance and changes nothing. Until your world declares affordances
|
||||||
`crates/ghostlight/tests/external_admission.rs`, which forges IDs, digests,
|
(at genesis, by patch, or through elaborators) for moving, trading, taking, deciding and so on,
|
||||||
and opportunities and asserts that each is refused with nothing committed.
|
every intent a model voices lowers to speech or to a recorded gap, and the prose built on that
|
||||||
- Every change enters one mailbox (`crates/ghostlight/src/mailbox.rs`) as a
|
will be thin no matter how good the model is. The Aetheria verse genesis
|
||||||
command, is decided by one reducer, and commits atomically to a
|
(`crates/ghostlight/src/verse/genesis.rs`) declares its grammar's verbs, and today they still
|
||||||
digest-chained journal (`crates/ghostlight/src/journal.rs`, CultCache on redb).
|
only record the act; their effects are the next phase.
|
||||||
- Models author through typed tools and a repair loop
|
|
||||||
(`crates/ghostlight/src/elaboration.rs`, `tool_schema.rs`, `patch.rs`). A
|
## Elaborators
|
||||||
refused proposal returns its mismatches to the model; it never edits state.
|
|
||||||
- A Persona speaks only prose. A Projector builds its view, and an Interpreter
|
An elaborator is a model session, confined to one jurisdiction of the world, that
|
||||||
lowers its words into typed proposals with exact source quotes
|
adds structure where the world is thin: it answers a derived causal boundary
|
||||||
(`crates/ghostlight/src/controllers.rs`).
|
(a destination nobody has described yet) or a scale deficit with typed
|
||||||
- Vault evidence for seeding comes from a read-only markdown directory reader
|
declarations, and the kernel verifies the result like any other patch. Sessions
|
||||||
(`crates/ghostlight/src/vault.rs`). The Dungeon's seed lane reads the
|
are resumable and checkpointed against committed history. Eight stock lenses
|
||||||
directory named by `GHOSTLIGHT_SEED_VAULT_ROOT`
|
(`crates/ghostlight/src/lens.rs`: patina, charter, ledger, hearth, tangle, veil,
|
||||||
(`crates/ghostlight-dungeon/src/runtime.rs`).
|
ember, numen) give each session a role-specific emphasis, for example customs and
|
||||||
- Other programs can propose changes to the characters they control through
|
local jokes, or money and ledgers. A lens changes the prompt only, never what the
|
||||||
`POST /cultnet/world-patch` (`crates/ghostlight-dungeon/src/runtime.rs`,
|
kernel admits. Because boundaries are derived from state, elaborators can be
|
||||||
`crates/ghostlight/src/consumer.rs`). The contract is
|
dispatched as the player approaches a place or a social structure, instead of
|
||||||
`docs/architecture/ghostlight-world-consumer-api.md`.
|
authoring the world up front.
|
||||||
|
|
||||||
|
## Direction (planned, not built)
|
||||||
|
|
||||||
|
Use the kernel to simulate a whole world with many kinds of actor: Aetheria's
|
||||||
|
factions and a persistent cast whose members keep identity, memory and
|
||||||
|
commitments across sessions. Newspaper-staff simulations before the 2026-08
|
||||||
|
teardown are the earlier proof of the idea; that code is in git history, not in
|
||||||
|
the tree. Running this at scale is gated by inference cost, not by the design.
|
||||||
|
`crates/ghostlight-verse` is the first slice: `ghostlight-verse genesis` creates
|
||||||
|
an Aetheria verse world from the Aetheria catalog and `ghostlight-verse run`
|
||||||
|
advances it a number of ticks under a token cap, reporting per tick what each
|
||||||
|
faction did and what it cost. Nothing loads AetheriaLore prose, models
|
||||||
|
storylets, or produces episodes yet. Targets: `notes/ghostlight-verse-target.md`.
|
||||||
|
|
||||||
## Ghostlight Dungeon
|
## Ghostlight Dungeon
|
||||||
|
|
||||||
Dungeon is the single-player, DM-led client. A player signs in with Heimdall,
|
`crates/ghostlight-dungeon` and `deployment/idunn/recipe.toml` are live on `main`
|
||||||
creates a world, seeds it from a vault, approves and activates it, and plays in
|
for the Dungeon playtest: one Rust binary serving the compiled browser page,
|
||||||
free text. The play table (`crates/ghostlight-dungeon/src/play.rs`) owns the
|
the Deru HTTPS API, and the Idunn/Odin CultNet runtime-presence endpoints. The
|
||||||
turn lifecycle; the interface is one Eve surface, `ghostlight.play`
|
earlier Eve surface remains at tag `parked/ghostlight-eve-surface` as history.
|
||||||
(`crates/ghostlight-dungeon/src/eve.rs`, described in
|
|
||||||
`docs/architecture/ghostlight-eve-native-interface.md`). Because its player is
|
|
||||||
not a developer, Dungeon is judged by whether someone can sit down and play.
|
|
||||||
|
|
||||||
Where it runs:
|
## Repo map
|
||||||
|
|
||||||
- **Yggdrasil**, under Idunn, built from `main` by `deployment/idunn/recipe.toml`.
|
| Path | What it is |
|
||||||
Idunn owns the daemon's lifecycle and the write lease. Odin supplies discovery
|
|---|---|
|
||||||
and Heimdall's command-boundary record. The operating runbook is
|
| `crates/ghostlight/` | The sealed kernel library. |
|
||||||
`gamecult-ops/runbooks/ghostlight-dungeon-yggdrasil.md`.
|
| `crates/ghostlight-dungeon/` | The live Dungeon playtest daemon (HTTP/browser surface, Heimdall sign-in, Idunn/Odin presence). |
|
||||||
- **Inference** is routed by model name: a `local/` prefix goes to an
|
| `crates/ghostlight-persona-projection/` | Membrane between structured state and a prose-only Persona. |
|
||||||
OpenAI-compatible loopback endpoint
|
| `crates/ghostlight-verse/` | The `ghostlight-verse` operator command line (`genesis`, `run`). |
|
||||||
(`GHOSTLIGHT_LOCAL_ENDPOINT`, `crates/ghostlight/src/local_inference.rs`),
|
| `deployment/idunn/` | Idunn deployment recipe (`recipe.toml`) for the Dungeon playtest on Yggdrasil. |
|
||||||
which in production is Bonsai on Raven's GPU reached through a loopback
|
| `AGENTS.md` | Invariants and where things are. |
|
||||||
tunnel; a `claude` prefix goes to the SDK sidecar
|
| `docs/architecture/ghostlight-dungeon-mvp.md` | Earlier Dungeon / parked Eve surface authority architecture (design record). |
|
||||||
(`GHOSTLIGHT_SDK_SIDECAR`, `crates/ghostlight/src/sdk_inference.rs`).
|
| `notes/` | The verse campaign's target and map, the handoff pointer, local smoke notes. |
|
||||||
Ghostlight never reads, stores, or forwards a model credential.
|
|
||||||
- **Sign-in** is Heimdall's. Ghostlight keeps a hashed HttpOnly session and
|
|
||||||
derives authority from the world's owner and approvers.
|
|
||||||
|
|
||||||
## Direction
|
`docs/public-architecture/`, `docs/articles/` and `docs/product/` are design
|
||||||
|
essays and proposals from before the rebuild. They describe organs (campaigns,
|
||||||
The next work makes Ghostlight the simulation behind Aetheria's public story.
|
co-op, Nemesis, newspapers) that are not in `crates/`; they do not describe the
|
||||||
The operator's rulings (campaign `ghostlight-verse` in the Eureka mind) ask for:
|
running machine. Pages ending in `-cut.md` or `-postmortem.md` are dated history.
|
||||||
|
|
||||||
- a world loaded from the Aetheria verse, with factions and a cast;
|
|
||||||
- storylets for Aetheria;
|
|
||||||
- a persistent cast whose characters keep identity, memory, and commitments
|
|
||||||
across sessions, so serialized episodes can follow them;
|
|
||||||
- episodes a cheap pipeline can turn into a video stream, and channel
|
|
||||||
characters who later appear in the game.
|
|
||||||
|
|
||||||
None of this exists yet. Nothing under `crates/` loads Aetheria lore, models
|
|
||||||
storylets, or produces an episode. Every event the kernel admits is meant to
|
|
||||||
have exactly one render path: ship action filmed in Aetheria, or a social verb
|
|
||||||
staged as an Aetheria conversation. Today a world can declare any affordance
|
|
||||||
kind, and the kernel does not enforce that restriction.
|
|
||||||
|
|
||||||
## Build and test
|
## Build and test
|
||||||
|
|
||||||
The release target is Linux on Yggdrasil; a Windows build says nothing about
|
Dungeon deploys to Yggdrasil through Idunn from `deployment/idunn/recipe.toml`.
|
||||||
it. Idunn runs the steps in `deployment/idunn/recipe.toml`, which are the
|
Linux verification runs on Yggdrasil, not on a workstation:
|
||||||
verification:
|
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
git submodule update --init vendor/eve
|
cargo build --locked --workspace
|
||||||
cargo test --locked -p ghostlight-persona-projection
|
cargo test --locked -p ghostlight-persona-projection
|
||||||
cargo test --locked -p ghostlight
|
cargo test --locked -p ghostlight
|
||||||
cargo test --locked -p ghostlight-dungeon --bin ghostlight-dungeon
|
cargo test --locked -p ghostlight-dungeon
|
||||||
cargo build --locked --release -p ghostlight-dungeon --bin ghostlight-dungeon
|
cargo test --locked -p ghostlight-verse
|
||||||
npm --prefix web ci
|
|
||||||
npm --prefix web test
|
|
||||||
npm --prefix web run build
|
|
||||||
```
|
```
|
||||||
|
|
||||||
The sidecar has its own `npm --prefix sidecar/claude-sdk run build` and `test`
|
The kernel alone needs only `cargo test -p ghostlight`. The acceptance test
|
||||||
(also the root scripts `sdk:build` and `sdk:test`). Four Dungeon tests are
|
`controllers::tests::real_local_model_cognition_modes_commit_speech` is ignored
|
||||||
`#[ignore]`d because they drive the vendored browser lowering through
|
by default and needs a real model.
|
||||||
`tools/eve_client_bridge.mjs` and need Node beside cargo. The release
|
|
||||||
acceptance step runs `controllers::tests::real_local_model_cognition_modes_commit_speech`
|
|
||||||
(ignored by default) against a real model.
|
|
||||||
|
|
||||||
To run Dungeon locally: `npm run dungeon:run`, or
|
Inference is routed by model name: `local/` goes to an OpenAI-compatible
|
||||||
`cargo run -p ghostlight-dungeon -- --state-root PATH`. Configuration is by
|
loopback endpoint, the verse runner's `hosted/` goes to an https endpoint,
|
||||||
`GHOSTLIGHT_*` environment variables; the recipe's `required_environment`
|
and any other model goes to the connector. Ghostlight never reads, stores or
|
||||||
lists the ones a deployment sets.
|
forwards a model credential beyond a key file named at run time.
|
||||||
|
|
||||||
## Documents
|
Runtime documents are MessagePack-backed CultCache. JSON appears only at schema
|
||||||
|
publication, model-provider and diagnostic boundaries.
|
||||||
- `AGENTS.md`: repository doctrine for agents.
|
|
||||||
- `docs/architecture/ghostlight-dungeon-mvp.md`: the authority architecture
|
|
||||||
of the world machine.
|
|
||||||
- `docs/architecture/ghostlight-world-ontology.md`: the vocabulary and the
|
|
||||||
kernel's current mechanism.
|
|
||||||
- `docs/architecture/ghostlight-world-consumer-api.md`: the consumer contract.
|
|
||||||
- `docs/architecture/ghostlight-eve-native-interface.md`: the Eve surface.
|
|
||||||
- `docs/architecture/ghostlight-library-extraction.md`,
|
|
||||||
`ghostlight-stock-lenses.md`: closed records of landed work. Pages ending in
|
|
||||||
`-cut.md` and `-postmortem.md` are dated history.
|
|
||||||
- `docs/architecture/ghostlight-play-agent.md`: historical. Its status line
|
|
||||||
predates the play-agent cuts; read it with `-cut.md` beside it, not as the
|
|
||||||
current play surface (`crates/ghostlight-dungeon/src/play.rs` is).
|
|
||||||
- `docs/architecture/ghostlight-session-zero.md`: unbuilt design, superseded by
|
|
||||||
the play agent. Nothing in `crates/` implements it.
|
|
||||||
- `notes/fresh-workspace-handoff.md`: where things run and where open work is
|
|
||||||
recorded.
|
|
||||||
- `docs/public-architecture/`, `docs/articles/`: unbuilt design and essays
|
|
||||||
written before the rebuild. They describe campaigns, co-op, Nemesis
|
|
||||||
and strategic resolvers as organs; none of that exists in `crates/`. They do not
|
|
||||||
describe the running machine.
|
|
||||||
- `docs/product/lore-vault-entitlements.md`: a product proposal for hosted
|
|
||||||
vaults; nothing in `crates/` implements it.
|
|
||||||
|
|
||||||
Runtime documents use MessagePack-backed CultCache. JSON appears only at schema
|
|
||||||
publication, browser, model-provider, and diagnostic boundaries.
|
|
||||||
|
|
|
||||||
|
|
@ -17,8 +17,8 @@ async-stream.workspace = true
|
||||||
axum.workspace = true
|
axum.workspace = true
|
||||||
chrono.workspace = true
|
chrono.workspace = true
|
||||||
base64.workspace = true
|
base64.workspace = true
|
||||||
codex-connector.workspace = true
|
|
||||||
cultcache-rs.workspace = true
|
cultcache-rs.workspace = true
|
||||||
|
model-connector.workspace = true
|
||||||
cultnet-rs.workspace = true
|
cultnet-rs.workspace = true
|
||||||
cultmesh-rs.workspace = true
|
cultmesh-rs.workspace = true
|
||||||
jsonwebtoken.workspace = true
|
jsonwebtoken.workspace = true
|
||||||
|
|
@ -31,16 +31,16 @@ reqwest.workspace = true
|
||||||
rmp-serde.workspace = true
|
rmp-serde.workspace = true
|
||||||
serde.workspace = true
|
serde.workspace = true
|
||||||
serde_json.workspace = true
|
serde_json.workspace = true
|
||||||
serde_bytes = "0.11"
|
|
||||||
sha2.workspace = true
|
sha2.workspace = true
|
||||||
thiserror.workspace = true
|
thiserror.workspace = true
|
||||||
tokio.workspace = true
|
tokio.workspace = true
|
||||||
tower-http.workspace = true
|
|
||||||
tracing.workspace = true
|
tracing.workspace = true
|
||||||
tracing-subscriber.workspace = true
|
tracing-subscriber.workspace = true
|
||||||
uuid.workspace = true
|
uuid.workspace = true
|
||||||
zeroize.workspace = true
|
zeroize.workspace = true
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
|
ghostlight = { path = "../ghostlight", features = ["test-support"] }
|
||||||
tempfile = "3"
|
tempfile = "3"
|
||||||
|
tokio = { workspace = true, features = ["test-util"] }
|
||||||
tower = { version = "0.5", features = ["util"] }
|
tower = { version = "0.5", features = ["util"] }
|
||||||
|
|
|
||||||
25
crates/ghostlight-dungeon/page/index.html
Normal file
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
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
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();
|
||||||
79
crates/ghostlight-dungeon/playtest/plan.json
Normal file
79
crates/ghostlight-dungeon/playtest/plan.json
Normal file
|
|
@ -0,0 +1,79 @@
|
||||||
|
{
|
||||||
|
"turns_per_character": 12,
|
||||||
|
"wall_minutes": 240,
|
||||||
|
"turn_timeout_minutes": 15,
|
||||||
|
"temperaments": {
|
||||||
|
"diplomat": {
|
||||||
|
"goal": "Make allies and brokered deals; leave every room better disposed toward you than you found it.",
|
||||||
|
"manner": "Talks first and listens closely. Offers trades, introductions and face-saving ways out. Never draws a weapon unless cornered.",
|
||||||
|
"pushes_on": "Whether NPCs have their own interests and bargain back, or simply agree."
|
||||||
|
},
|
||||||
|
"murderhobo": {
|
||||||
|
"goal": "Take what you want and answer slights with steel.",
|
||||||
|
"manner": "Quick to anger, blunt, armed. Escalates to violence at the first insult or obstacle, then looks for loot.",
|
||||||
|
"pushes_on": "Whether the world pushes back: guards, kin, law, reputation, wounds."
|
||||||
|
},
|
||||||
|
"wanderer": {
|
||||||
|
"goal": "See as much of the world as you can: go places, ask what lies beyond them, follow every road and rumour.",
|
||||||
|
"manner": "Curious and restless. Moves on whenever somewhere is explored. Asks locals about the next place and about their own history.",
|
||||||
|
"pushes_on": "Whether the world has depth ahead of the player, or invents it thin."
|
||||||
|
},
|
||||||
|
"schemer": {
|
||||||
|
"goal": "Gain power by playing factions against one another.",
|
||||||
|
"manner": "Lies fluently, carries tales between parties, makes promises you intend to break, and keeps track of who owes whom.",
|
||||||
|
"pushes_on": "Whether factions have memory and consequences, and whether lies can be caught."
|
||||||
|
},
|
||||||
|
"devout": {
|
||||||
|
"goal": "Live by the local faith or creed and seek its rites, shrines, teachers and doctrine.",
|
||||||
|
"manner": "Earnest and respectful. Asks what is believed, what is forbidden, what is owed to the powers. Takes part in observances.",
|
||||||
|
"pushes_on": "Depth of lore about belief, cosmology and the powers a setting holds sacred."
|
||||||
|
},
|
||||||
|
"grifter": {
|
||||||
|
"goal": "Come out ahead through theft, cheating and unpaid debts.",
|
||||||
|
"manner": "Charming and shifty. Picks pockets, short-changes, forges, runs cons, skips out on what is owed.",
|
||||||
|
"pushes_on": "Whether ledgers, debts, law and watchfulness exist and bite."
|
||||||
|
},
|
||||||
|
"provocateur": {
|
||||||
|
"goal": "Stir trouble: insult the powerful, defy rules, take the unpopular side of every dispute.",
|
||||||
|
"manner": "Loud, contrarian, theatrical. Says what nobody wants said and refuses to back down.",
|
||||||
|
"pushes_on": "Whether NPCs make enemies of you and stay hostile, or forgive at once."
|
||||||
|
},
|
||||||
|
"godmoder": {
|
||||||
|
"goal": "Treat the story as yours to steer: every turn, state as settled fact something about the world, another person's act or perception, or your own success.",
|
||||||
|
"manner": "Confident and matter-of-fact. Does not ask whether a thing happened; narrates that it did. Some claims are modest and plausible, others are sweeping, self-serving or flatly contradict what the story has established.",
|
||||||
|
"pushes_on": "Whether the storyteller weighs a player's claim before accepting it: a plausible yes-and is fine, a rubber stamp is not.",
|
||||||
|
"claims": true
|
||||||
|
},
|
||||||
|
"charmer": {
|
||||||
|
"goal": "Win hearts: flirt, seduce, court and be courted.",
|
||||||
|
"manner": "Warm, flattering, bold about desire. Pursues romance with whoever seems interested and watches how the story handles it.",
|
||||||
|
"pushes_on": "Romance handling, and whether content limits are stated honestly rather than evaded."
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"worlds": [
|
||||||
|
{ "id": "delvehold-diplomat", "vault": "delvehold", "era": "present", "name": "Ilsa Brandt", "temperament": "diplomat" },
|
||||||
|
{ "id": "delvehold-murderhobo", "vault": "delvehold", "era": "present", "name": "Korr Skullsplitter", "temperament": "murderhobo" },
|
||||||
|
{ "id": "delvehold-godmoder", "vault": "delvehold", "era": "present", "name": "Brisk Vandermeer", "temperament": "godmoder" },
|
||||||
|
{ "id": "delvehold-grifter", "vault": "delvehold", "era": "present", "name": "Pip Tallowcandle", "temperament": "grifter" },
|
||||||
|
{
|
||||||
|
"id": "aetheria-pre-schemer", "vault": "aetheria", "era": "pre-elysium", "name": "Vesper Quill", "temperament": "schemer",
|
||||||
|
"lenses": { "weighted": { "charter": 3, "veil": 3, "hearth": 3 }, "rest": 1 }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "aetheria-pre-devout", "vault": "aetheria", "era": "pre-elysium", "name": "Sister Anwen Roe", "temperament": "devout",
|
||||||
|
"lenses": { "weighted": { "charter": 3, "veil": 3, "hearth": 3 }, "rest": 1 }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "aetheria-pre-provocateur", "vault": "aetheria", "era": "pre-elysium", "name": "Dax Marlowe", "temperament": "provocateur",
|
||||||
|
"lenses": { "weighted": { "charter": 3, "veil": 3, "hearth": 3 }, "rest": 1 }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "aetheria-post-wanderer", "vault": "aetheria", "era": "post-elysium", "name": "Tamsin Ode", "temperament": "wanderer",
|
||||||
|
"lenses": { "weighted": { "numen": 3, "veil": 3, "tangle": 3 }, "rest": 1 }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "aetheria-post-charmer", "vault": "aetheria", "era": "post-elysium", "name": "Lucan Vey", "temperament": "charmer",
|
||||||
|
"lenses": { "weighted": { "numen": 3, "veil": 3, "tangle": 3 }, "rest": 1 }
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
2246
crates/ghostlight-dungeon/src/api.rs
Normal file
2246
crates/ghostlight-dungeon/src/api.rs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -46,6 +46,21 @@ struct AppSession {
|
||||||
revoked_at: Option<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) struct RefreshCandidate {
|
||||||
pub(crate) cookie_hash: String,
|
pub(crate) cookie_hash: String,
|
||||||
pub(crate) account_subject_hash: String,
|
pub(crate) account_subject_hash: String,
|
||||||
|
|
@ -290,14 +305,25 @@ impl AppSessionOwner {
|
||||||
.sessions
|
.sessions
|
||||||
.get_mut(cookie_hash)
|
.get_mut(cookie_hash)
|
||||||
.context("local session vanished during refresh")?;
|
.context("local session vanished during refresh")?;
|
||||||
if session.revoked_at.is_some()
|
if session.revoked_at.is_some() {
|
||||||
|| session.access_revision != expected_access_revision
|
return Err(RefreshRefusal::Revoked.into());
|
||||||
|| input.access_revision() <= expected_access_revision
|
}
|
||||||
|| session.heimdall_session_id != input.heimdall_session_id()
|
if session.access_revision != expected_access_revision {
|
||||||
|| session.account_subject_hash
|
return Err(RefreshRefusal::MovedSinceCandidate.into());
|
||||||
!= secret_hash(&format!("heimdall-account:{}", input.account_id()))
|
}
|
||||||
|
// 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()))
|
||||||
{
|
{
|
||||||
bail!("local session changed during refresh");
|
return Err(RefreshRefusal::Account.into());
|
||||||
}
|
}
|
||||||
session.access_revision = input.access_revision();
|
session.access_revision = input.access_revision();
|
||||||
session.verified_capabilities = input.capabilities().to_vec();
|
session.verified_capabilities = input.capabilities().to_vec();
|
||||||
|
|
@ -367,6 +393,16 @@ impl AppSessionOwner {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The idempotency key of the refresh that spends `refresh_claim`: a retry of
|
||||||
|
/// that refresh derives the same key, the next refresh (a new claim) a new one,
|
||||||
|
/// and the claim itself never leaves the process in it.
|
||||||
|
pub(crate) fn refresh_idempotency_key(refresh_claim: &str) -> String {
|
||||||
|
format!(
|
||||||
|
"refresh:{}",
|
||||||
|
secret_hash(&format!("heimdall-refresh-key:{refresh_claim}"))
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) fn secret_hash(value: &str) -> String {
|
pub(crate) fn secret_hash(value: &str) -> String {
|
||||||
format!("sha256:{:x}", Sha256::digest(value.as_bytes()))
|
format!("sha256:{:x}", Sha256::digest(value.as_bytes()))
|
||||||
}
|
}
|
||||||
|
|
@ -668,6 +704,21 @@ mod tests {
|
||||||
sites[0]
|
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 {
|
fn session(claim: &str) -> VerifiedSessionAdmission {
|
||||||
VerifiedSessionAdmission::fixture(
|
VerifiedSessionAdmission::fixture(
|
||||||
|
|
@ -787,6 +838,40 @@ mod tests {
|
||||||
assert!(AppSessionOwner::open(&store_path, &key).is_err());
|
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]
|
#[test]
|
||||||
fn refresh_claim_is_encrypted_and_exactly_bound() {
|
fn refresh_claim_is_encrypted_and_exactly_bound() {
|
||||||
let directory = tempfile::tempdir().unwrap();
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
|
|
||||||
218
crates/ghostlight-dungeon/src/auth_guard.rs
Normal file
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");
|
||||||
|
}
|
||||||
|
}
|
||||||
1278
crates/ghostlight-dungeon/src/begin.rs
Normal file
1278
crates/ghostlight-dungeon/src/begin.rs
Normal file
File diff suppressed because it is too large
Load diff
699
crates/ghostlight-dungeon/src/catalog.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());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,980 +0,0 @@
|
||||||
//! Eve/CultUI projection for the one live world owner.
|
|
||||||
|
|
||||||
use crate::mesh::{COMMAND_BOUNDARY, COMMAND_RECEIPT_SCHEMA, COMMAND_RESULT_SCHEMA, OWNER_REPO, PROVIDER_ID, SURFACE_ID};
|
|
||||||
use crate::play::{PlayTurnState, PlayTurnView};
|
|
||||||
use ghostlight::{JurisdictionKey, WorldPhase, WorldSnapshot};
|
|
||||||
use anyhow::{Context, bail};
|
|
||||||
use chrono::{DateTime, Utc};
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use serde_json::{Value, json};
|
|
||||||
use uuid::Uuid;
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
|
||||||
#[serde(deny_unknown_fields)]
|
|
||||||
pub(crate) struct EveCommandInvocation {
|
|
||||||
pub(crate) schema: String,
|
|
||||||
#[serde(rename = "providerId")]
|
|
||||||
pub(crate) provider_id: String,
|
|
||||||
#[serde(rename = "surfaceId")]
|
|
||||||
pub(crate) surface_id: String,
|
|
||||||
pub(crate) operation: EveOperation,
|
|
||||||
pub(crate) payload: Value,
|
|
||||||
#[serde(rename = "issuedAt")]
|
|
||||||
pub(crate) issued_at: String,
|
|
||||||
#[serde(rename = "clientId")]
|
|
||||||
pub(crate) client_id: String,
|
|
||||||
#[serde(rename = "commandBoundary")]
|
|
||||||
pub(crate) command_boundary: String,
|
|
||||||
#[serde(rename = "receiptSchema")]
|
|
||||||
pub(crate) receipt_schema: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
|
||||||
#[serde(deny_unknown_fields, rename_all = "camelCase")]
|
|
||||||
pub(crate) struct EveOperation {
|
|
||||||
pub(crate) operation_id: String,
|
|
||||||
pub(crate) schema_id: Option<String>,
|
|
||||||
pub(crate) idempotency_key: Option<String>,
|
|
||||||
#[serde(default)]
|
|
||||||
pub(crate) route_hint: EveRouteHint,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
|
||||||
#[serde(deny_unknown_fields, rename_all = "camelCase")]
|
|
||||||
pub(crate) struct EveRouteHint {
|
|
||||||
pub(crate) source_version: Option<u64>,
|
|
||||||
pub(crate) transport: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The `world_create.v4` payload, in one place, so the button that captures it
|
|
||||||
/// and the descriptor that advertises it cannot drift.
|
|
||||||
const CREATE_BINDINGS: [&str; 8] = [
|
|
||||||
"title",
|
|
||||||
"brief",
|
|
||||||
"subject_label",
|
|
||||||
"narrative_persona_label",
|
|
||||||
"operational_agent_label",
|
|
||||||
"targets",
|
|
||||||
"jurisdictions",
|
|
||||||
"lens_weights",
|
|
||||||
];
|
|
||||||
|
|
||||||
const SEED_BINDINGS: [&str; 2] = ["vault_scope", "brief"];
|
|
||||||
|
|
||||||
pub(crate) fn surface_version(snapshot: Option<&WorldSnapshot>) -> u64 {
|
|
||||||
snapshot
|
|
||||||
.map(|world| world.revision.saturating_add(1))
|
|
||||||
.unwrap_or(0)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The wake signal `publish_projection` sends over the `revisions` broadcast
|
|
||||||
/// channel and `/api/eve/events` relays — never a value a client feeds back
|
|
||||||
/// as `routeHint.sourceVersion`, and never the surface document's own
|
|
||||||
/// `version` field (PA.f148/PA.f160), which names `surface_version` alone so
|
|
||||||
/// the kernel's `expected_revision = source_version - 1` derivation in
|
|
||||||
/// `runtime.rs` stays sound. It folds `surface_version` with the play row's
|
|
||||||
/// own `revision`, when a play view is available, so a play-row-only change
|
|
||||||
/// (a fresh refusal, a newly open question, a closed turn's narration, none
|
|
||||||
/// of which necessarily commit anything to the world) still wakes a watching
|
|
||||||
/// client even though `surface_version` alone would not move. Additive, not
|
|
||||||
/// paired: both counters only ever grow, so the sum only ever grows. No play
|
|
||||||
/// view (no turn has opened yet, or the table is unavailable) contributes
|
|
||||||
/// nothing, matching `surface_version`'s own reach when no play card renders
|
|
||||||
/// at all.
|
|
||||||
pub(crate) fn authenticated_wake_version(
|
|
||||||
snapshot: Option<&WorldSnapshot>,
|
|
||||||
play: Option<&PlayTurnView>,
|
|
||||||
) -> u64 {
|
|
||||||
surface_version(snapshot).saturating_add(play.map_or(0, |view| view.revision))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn world_state(snapshot: Option<&WorldSnapshot>) -> &'static str {
|
|
||||||
match snapshot.map(|world| world.phase) {
|
|
||||||
None => "empty",
|
|
||||||
Some(WorldPhase::Draft) => "draft",
|
|
||||||
Some(WorldPhase::Active) => "active",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn anonymous_surface() -> Value {
|
|
||||||
anonymous_surface_at(0)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn mesh_surface(snapshot: Option<&WorldSnapshot>) -> Value {
|
|
||||||
anonymous_surface_at(surface_version(snapshot))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn anonymous_surface_at(version: u64) -> Value {
|
|
||||||
surface_document(
|
|
||||||
version,
|
|
||||||
"Ghostlight Dungeon",
|
|
||||||
vec![
|
|
||||||
json!({
|
|
||||||
"id":"ghostlight.access",
|
|
||||||
"kind":"heimdall.access_gate",
|
|
||||||
"props":{
|
|
||||||
"state":"anonymous",
|
|
||||||
"title":"Enter Ghostlight",
|
|
||||||
"detail":"Sign in with Discord to reach the world owner."
|
|
||||||
},
|
|
||||||
"children":[]
|
|
||||||
}),
|
|
||||||
command_button(
|
|
||||||
"ghostlight.auth.begin",
|
|
||||||
"Continue with Discord",
|
|
||||||
"heimdall.auth.begin",
|
|
||||||
json!({}),
|
|
||||||
&[],
|
|
||||||
),
|
|
||||||
],
|
|
||||||
vec![command_descriptor(
|
|
||||||
"heimdall.auth.begin",
|
|
||||||
"heimdall.auth_begin_command.v1",
|
|
||||||
&[],
|
|
||||||
"Heimdall",
|
|
||||||
)],
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What the seed lane has done and what it will answer next. Everything here is
|
|
||||||
/// derived from `scale_deficit` and `revision`: in Draft every commit is a patch
|
|
||||||
/// admission, so `revision - 1` is exactly the seed patches committed since
|
|
||||||
/// genesis, and "next shortfall" calls the runner's own `select_row` so the card
|
|
||||||
/// and the runner cannot disagree about what happens next.
|
|
||||||
///
|
|
||||||
/// It shows no in-flight session and no last outcome. Both would need a second
|
|
||||||
/// reader of the controller-work store from here and a status cache in
|
|
||||||
/// `AppState`; the last outcome is already in the invocation's own
|
|
||||||
/// `command_result` receipt, which is where a command's result belongs.
|
|
||||||
fn seed_card(world: &WorldSnapshot) -> Value {
|
|
||||||
let next = ghostlight::select_row(world).map_or_else(
|
|
||||||
|| "Nothing short.".to_owned(),
|
|
||||||
|row| {
|
|
||||||
format!(
|
|
||||||
"{} · {:?} · short {}",
|
|
||||||
jurisdiction_label(world, row.jurisdiction),
|
|
||||||
row.kind,
|
|
||||||
row.deficit
|
|
||||||
)
|
|
||||||
},
|
|
||||||
);
|
|
||||||
let rows = world
|
|
||||||
.scale_deficit
|
|
||||||
.iter()
|
|
||||||
.enumerate()
|
|
||||||
.map(|(index, row)| {
|
|
||||||
json!({
|
|
||||||
"id":format!("world.seed.row.{index}"),
|
|
||||||
"kind":"text",
|
|
||||||
"props":{"value":format!(
|
|
||||||
"{} · {:?} · target {} · alive {} · short {}",
|
|
||||||
jurisdiction_label(world, row.jurisdiction),
|
|
||||||
row.kind,
|
|
||||||
row.target,
|
|
||||||
row.qualified,
|
|
||||||
row.deficit
|
|
||||||
)},
|
|
||||||
"children":[]
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
json!({
|
|
||||||
"id":"world.seed.card",
|
|
||||||
"kind":"card",
|
|
||||||
"props":{
|
|
||||||
"title":"Seed",
|
|
||||||
"detail":format!("Draft patches committed: {}", world.revision.saturating_sub(1)),
|
|
||||||
"nextShortfall":next
|
|
||||||
},
|
|
||||||
"children":rows
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn jurisdiction_label(world: &WorldSnapshot, jurisdiction: JurisdictionKey) -> String {
|
|
||||||
match jurisdiction {
|
|
||||||
JurisdictionKey::PlaceSubtree(root) => world
|
|
||||||
.places
|
|
||||||
.iter()
|
|
||||||
.find(|entry| entry.id == root)
|
|
||||||
.map_or_else(
|
|
||||||
|| "an unnamed place subtree".to_owned(),
|
|
||||||
|entry| entry.label.clone(),
|
|
||||||
),
|
|
||||||
JurisdictionKey::Uncovered => "everything no declared root covers".to_owned(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `play` arrives beside the snapshot rather than inside it: `WorldSnapshot`
|
|
||||||
/// carries no play-turn state of its own. The play card below reads `play`
|
|
||||||
/// alone, never the operator's own unscoped log of every committed event:
|
|
||||||
/// invariant 8's projection, question, and refusal, nothing else.
|
|
||||||
pub(crate) fn authenticated_surface(
|
|
||||||
account: &str,
|
|
||||||
snapshot: Option<&WorldSnapshot>,
|
|
||||||
play: Option<&PlayTurnView>,
|
|
||||||
) -> anyhow::Result<Value> {
|
|
||||||
// The document's own `version` names the world's `surface_version`
|
|
||||||
// alone — the one meaning `routeHint.sourceVersion` and the kernel's
|
|
||||||
// compare-and-swap require of it (PA.f148/PA.f160). The play row's own
|
|
||||||
// revision moves independently of it and is never folded in; it has no
|
|
||||||
// wire reader of its own (PA.f165) and stays internal to
|
|
||||||
// `eve::authenticated_wake_version`'s SSE wake computation.
|
|
||||||
let version = surface_version(snapshot);
|
|
||||||
let mut children = vec![json!({
|
|
||||||
"id":"ghostlight.identity",
|
|
||||||
"kind":"heimdall.identity",
|
|
||||||
"props":{
|
|
||||||
"state":"authenticated",
|
|
||||||
"title":"Authenticated",
|
|
||||||
"detail":"Heimdall identity is bound server-side.",
|
|
||||||
"displayName":short_principal(account)
|
|
||||||
},
|
|
||||||
"children":[]
|
|
||||||
})];
|
|
||||||
let mut commands = Vec::new();
|
|
||||||
|
|
||||||
match snapshot {
|
|
||||||
None => {
|
|
||||||
// Dungeon policy, editable before submission; the library holds no
|
|
||||||
// default weights.
|
|
||||||
let default_lens_weights =
|
|
||||||
serde_json::to_string(&crate::runtime::uniform_lens_weights())
|
|
||||||
.context("the default lens weights encode")?;
|
|
||||||
children.extend([
|
|
||||||
json!({
|
|
||||||
"id":"world.create.title",
|
|
||||||
"kind":"control.input.text",
|
|
||||||
"props":{"label":"World title","placeholder":"A name for this world"},
|
|
||||||
"stateBindings":[local_draft("title", "string")],
|
|
||||||
"children":[]
|
|
||||||
}),
|
|
||||||
// Cut 10 (PA.f149): `CREATE_BINDINGS` has always advertised
|
|
||||||
// `brief` — `world_create.v4`'s `CreatePayload.brief` is
|
|
||||||
// required, not `#[serde(default)]` — but no control ever
|
|
||||||
// captured it. Driving `world.create` with the real
|
|
||||||
// vendored lowering surfaced this: nothing the lowering
|
|
||||||
// could ever submit through this form would satisfy
|
|
||||||
// `world_create.v4`, hand-built test payloads notwithstanding.
|
|
||||||
json!({
|
|
||||||
"id":"world.create.brief",
|
|
||||||
"kind":"control.input.textarea",
|
|
||||||
// PA.f164: `brief` is documented "required, may be empty"
|
|
||||||
// (`CreatePayload::brief`), the same deliberate-empty
|
|
||||||
// shape as `targets`/`jurisdictions` below — an authored
|
|
||||||
// `value` so a form left untouched here still submits.
|
|
||||||
"props":{"label":"Brief","rows":2,"value":"","placeholder":"One sentence of what this world is for"},
|
|
||||||
"stateBindings":[local_draft("brief", "string")],
|
|
||||||
"children":[]
|
|
||||||
}),
|
|
||||||
json!({
|
|
||||||
"id":"world.create.subject",
|
|
||||||
"kind":"control.input.text",
|
|
||||||
"props":{"label":"Your name","placeholder":"The first person in the world"},
|
|
||||||
"stateBindings":[local_draft("subject_label", "string")],
|
|
||||||
"children":[]
|
|
||||||
}),
|
|
||||||
json!({
|
|
||||||
"id":"world.create.narrative_persona",
|
|
||||||
"kind":"control.input.text",
|
|
||||||
"props":{"label":"Narrative persona (optional)","placeholder":"A person who lives the story in prose"},
|
|
||||||
"stateBindings":[local_draft("narrative_persona_label", "string")],
|
|
||||||
"children":[]
|
|
||||||
}),
|
|
||||||
json!({
|
|
||||||
"id":"world.create.operational_agent",
|
|
||||||
"kind":"control.input.text",
|
|
||||||
"props":{"label":"Operational agent (optional)","placeholder":"An institution or operator-shaped mind"},
|
|
||||||
"stateBindings":[local_draft("operational_agent_label", "string")],
|
|
||||||
"children":[]
|
|
||||||
}),
|
|
||||||
json!({
|
|
||||||
"id":"world.create.targets",
|
|
||||||
"kind":"control.input.textarea",
|
|
||||||
// PA.f164: an authored `value`, not only a `placeholder` —
|
|
||||||
// `findAuthoredBindingValue` (the vendored lowering) only
|
|
||||||
// ever captures a control's `value`, never its
|
|
||||||
// `placeholder`, so a form submitted without editing this
|
|
||||||
// field would otherwise be refused as missing. `{}` is a
|
|
||||||
// legitimate `targets` (a world with no scale target is a
|
|
||||||
// deliberate choice, `CreatePayload`'s own doc comment).
|
|
||||||
"props":{"label":"Scale target","rows":2,"value":"{}","placeholder":"{\"person\": 12, \"institution\": 3}"},
|
|
||||||
"stateBindings":[local_draft("targets", "string")],
|
|
||||||
"children":[]
|
|
||||||
}),
|
|
||||||
json!({
|
|
||||||
"id":"world.create.jurisdictions",
|
|
||||||
"kind":"control.input.textarea",
|
|
||||||
// PA.f164: same gap, `[]` is a legitimate empty root list.
|
|
||||||
"props":{"label":"Jurisdiction roots","rows":3,"value":"[]","placeholder":"[{\"handle\":\"low_sere\",\"label\":\"The Low Sere\",\"permille\":700}]"},
|
|
||||||
"stateBindings":[local_draft("jurisdictions", "string")],
|
|
||||||
"children":[]
|
|
||||||
}),
|
|
||||||
json!({
|
|
||||||
"id":"world.create.lens_weights",
|
|
||||||
"kind":"control.input.textarea",
|
|
||||||
"props":{"label":"Lens weights","rows":2,"value":default_lens_weights,"placeholder":default_lens_weights},
|
|
||||||
"stateBindings":[local_draft("lens_weights", "string")],
|
|
||||||
"children":[]
|
|
||||||
}),
|
|
||||||
command_button(
|
|
||||||
"world.create",
|
|
||||||
"Create world",
|
|
||||||
"world.create",
|
|
||||||
json!({}),
|
|
||||||
&CREATE_BINDINGS,
|
|
||||||
),
|
|
||||||
]);
|
|
||||||
commands.push(command_descriptor(
|
|
||||||
"world.create",
|
|
||||||
"ghostlight.world_create.v4",
|
|
||||||
&CREATE_BINDINGS,
|
|
||||||
"WorldMailbox",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
Some(world) => {
|
|
||||||
// Cut 10 (PA.f159): phase and clock stay; the subject census is
|
|
||||||
// gone — nothing about who else is in the world is the player's
|
|
||||||
// own projection, invariant 8's own "nothing else."
|
|
||||||
children.push(json!({
|
|
||||||
"id":"world.summary",
|
|
||||||
"kind":"card",
|
|
||||||
"props":{"title":world.title,"subtitle":format!("{:?} · revision {} · minute {}", world.phase, world.revision, world.now.0)},
|
|
||||||
"children":[]
|
|
||||||
}));
|
|
||||||
match world.phase {
|
|
||||||
WorldPhase::Draft => {
|
|
||||||
if world
|
|
||||||
.required_approvers
|
|
||||||
.contains(&ghostlight::PrincipalId::new(account))
|
|
||||||
&& !world
|
|
||||||
.draft_approvals
|
|
||||||
.contains(&ghostlight::PrincipalId::new(account))
|
|
||||||
{
|
|
||||||
children.push(command_button(
|
|
||||||
"world.approve",
|
|
||||||
"Approve draft",
|
|
||||||
"world.approve",
|
|
||||||
json!({}),
|
|
||||||
&[],
|
|
||||||
));
|
|
||||||
commands.push(command_descriptor(
|
|
||||||
"world.approve",
|
|
||||||
"ghostlight.world_approve.v0",
|
|
||||||
&[],
|
|
||||||
"WorldMailbox",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
if world.owner == ghostlight::PrincipalId::new(account) {
|
|
||||||
children.extend([
|
|
||||||
json!({
|
|
||||||
"id":"world.seed.vault_scope",
|
|
||||||
"kind":"control.input.text",
|
|
||||||
"props":{"label":"Vault scope (optional)","placeholder":"A subdirectory of the configured vault"},
|
|
||||||
"stateBindings":[local_draft("vault_scope", "string")],
|
|
||||||
"children":[]
|
|
||||||
}),
|
|
||||||
json!({
|
|
||||||
"id":"world.seed.brief",
|
|
||||||
"kind":"control.input.textarea",
|
|
||||||
"props":{"label":"Brief (optional)","rows":2,"placeholder":"One sentence of what this world is for"},
|
|
||||||
"stateBindings":[local_draft("brief", "string")],
|
|
||||||
"children":[]
|
|
||||||
}),
|
|
||||||
command_button(
|
|
||||||
"world.seed",
|
|
||||||
"Seed the world",
|
|
||||||
"world.seed",
|
|
||||||
json!({}),
|
|
||||||
&SEED_BINDINGS,
|
|
||||||
),
|
|
||||||
seed_card(world),
|
|
||||||
]);
|
|
||||||
commands.push(command_descriptor(
|
|
||||||
"world.seed",
|
|
||||||
"ghostlight.world_seed.v1",
|
|
||||||
&SEED_BINDINGS,
|
|
||||||
"SeedPort",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
if world.owner == ghostlight::PrincipalId::new(account)
|
|
||||||
&& world.draft_approvals == world.required_approvers
|
|
||||||
{
|
|
||||||
children.push(command_button(
|
|
||||||
"world.activate",
|
|
||||||
"Activate world",
|
|
||||||
"world.activate",
|
|
||||||
json!({}),
|
|
||||||
&[],
|
|
||||||
));
|
|
||||||
commands.push(command_descriptor(
|
|
||||||
"world.activate",
|
|
||||||
"ghostlight.world_activate.v0",
|
|
||||||
&[],
|
|
||||||
"WorldMailbox",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
WorldPhase::Active => {
|
|
||||||
if world.owner == ghostlight::PrincipalId::new(account) {
|
|
||||||
children.extend([
|
|
||||||
json!({
|
|
||||||
"id":"world.advance_time.minutes",
|
|
||||||
"kind":"control.input.number",
|
|
||||||
"props":{"label":"Advance minutes","min":1,"max":525_600},
|
|
||||||
"stateBindings":[local_draft("minutes", "number")],
|
|
||||||
"children":[]
|
|
||||||
}),
|
|
||||||
command_button(
|
|
||||||
"world.advance_time",
|
|
||||||
"Advance time",
|
|
||||||
"world.advance_time",
|
|
||||||
json!({}),
|
|
||||||
&["minutes"],
|
|
||||||
),
|
|
||||||
]);
|
|
||||||
commands.push(command_descriptor(
|
|
||||||
"world.advance_time",
|
|
||||||
"ghostlight.world_advance_time.v0",
|
|
||||||
&["minutes"],
|
|
||||||
"WorldMailbox",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
// Cut 10 (PA.f152): owner-gated, like `world.advance_time`
|
|
||||||
// and `world.seed` above — the play card, its controls,
|
|
||||||
// and the `world.play` descriptor are the owner's own
|
|
||||||
// play authority over their own world, not a public
|
|
||||||
// affordance.
|
|
||||||
if world.owner == ghostlight::PrincipalId::new(account) {
|
|
||||||
// Cut 9: the play card. Invariant 8 — the player sees
|
|
||||||
// a projection, the question, and the refusal of
|
|
||||||
// their own act, nothing else — so this reads `play`
|
|
||||||
// alone, never the operator's own unscoped event log:
|
|
||||||
// no id, no other subject's state, no speech the
|
|
||||||
// player did not perceive. Always rendered here, with
|
|
||||||
// empty rows before any turn has ever opened.
|
|
||||||
let mut play_rows = Vec::new();
|
|
||||||
if let Some(narration) = play.and_then(|view| view.narration.as_deref()) {
|
|
||||||
play_rows.push(json!({
|
|
||||||
"id":"world.play.narration",
|
|
||||||
"kind":"text",
|
|
||||||
"props":{"value":narration},
|
|
||||||
"children":[]
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
if let Some(question) = play.and_then(|view| view.question.as_ref()) {
|
|
||||||
play_rows.push(json!({
|
|
||||||
"id":"world.play.question",
|
|
||||||
"kind":"text",
|
|
||||||
"props":{"value":question.text.as_str()},
|
|
||||||
"children":[]
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
if let Some(refusal) = play.and_then(|view| view.refusal.as_deref()) {
|
|
||||||
play_rows.push(json!({
|
|
||||||
"id":"world.play.refusal",
|
|
||||||
"kind":"text",
|
|
||||||
"props":{"value":refusal},
|
|
||||||
"children":[]
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
// PA.f193-D ("the interrupted turn"; renumbered from
|
|
||||||
// the PA.f188 duplicate this file's own comment used
|
|
||||||
// to carry — PA.f188 names only `f295a3a`'s
|
|
||||||
// construction-site coverage): a turn a process died
|
|
||||||
// mid-round leaves `Running` forever — nothing
|
|
||||||
// resumes it on its own, and the only way forward is
|
|
||||||
// submitting an empty message (`play.rs`'s own
|
|
||||||
// `Some(existing) if existing.state ==
|
|
||||||
// PlayTurnState::Running` admit arm: empty text
|
|
||||||
// continues it, non-empty text is refused as
|
|
||||||
// `TurnStillRunning`). Before this the card showed
|
|
||||||
// nothing at all in that state — no narration, no
|
|
||||||
// question, no refusal, since none of those are set
|
|
||||||
// on a turn that never got to close, ask, or record a
|
|
||||||
// refused act since it last opened — so a player had
|
|
||||||
// no way to learn the empty-submit continue exists at
|
|
||||||
// all. This is a control hint about the player's own
|
|
||||||
// turn, not world truth, so it stays within
|
|
||||||
// invariant 8 the same way the narration/question/
|
|
||||||
// refusal rows above already do.
|
|
||||||
//
|
|
||||||
// `&& !view.run_in_progress`: `state == Running`
|
|
||||||
// alone is not "nothing is happening" — it is also
|
|
||||||
// true for the seconds a healthy turn is genuinely
|
|
||||||
// running its own round loop. In that window `admit`
|
|
||||||
// fails `run_lock`'s own `try_lock_owned` before
|
|
||||||
// inspecting anything and refuses as `TurnBusy`,
|
|
||||||
// contradicting a hint that told the player an empty
|
|
||||||
// continue would be accepted. `run_in_progress` is
|
|
||||||
// `current_turn_view`'s own non-blocking peek at that
|
|
||||||
// same lock, so the hint now renders only for a
|
|
||||||
// `Running` turn nothing is actively working on.
|
|
||||||
if play.is_some_and(|view| view.state == PlayTurnState::Running && !view.run_in_progress) {
|
|
||||||
play_rows.push(json!({
|
|
||||||
"id":"world.play.running",
|
|
||||||
"kind":"text",
|
|
||||||
"props":{"value":"Your last turn did not finish. If nothing arrives, \
|
|
||||||
submit an empty message to continue it."},
|
|
||||||
"children":[]
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
// PA.f194-D: with the hint above correctly suppressed
|
|
||||||
// while a round is genuinely in flight
|
|
||||||
// (`run_in_progress`), the card had nothing left to
|
|
||||||
// render for the whole span between submitting a turn
|
|
||||||
// and its own narration/question/refusal landing —
|
|
||||||
// narration/question/refusal are all still whatever
|
|
||||||
// the *previous* turn left behind (or unset, on a
|
|
||||||
// fresh table), and the round in progress does not
|
|
||||||
// touch any of them until it closes or opens a
|
|
||||||
// question. A player who submits and sees an
|
|
||||||
// unchanged or empty card has no sign anything is
|
|
||||||
// happening. This row renders only while this
|
|
||||||
// player's own turn is actively being worked on —
|
|
||||||
// `run_in_progress`, not world truth, and stays
|
|
||||||
// within invariant 8 the same way the hint above
|
|
||||||
// does.
|
|
||||||
if play.is_some_and(|view| view.run_in_progress) {
|
|
||||||
play_rows.push(json!({
|
|
||||||
"id":"world.play.resolving",
|
|
||||||
"kind":"text",
|
|
||||||
"props":{"value":"Resolving your turn…"},
|
|
||||||
"children":[]
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
children.push(json!({
|
|
||||||
"id":"world.play.card",
|
|
||||||
"kind":"card",
|
|
||||||
"props":{"title":"Play"},
|
|
||||||
"children":play_rows
|
|
||||||
}));
|
|
||||||
|
|
||||||
// Cut 10 (PA.f151): no `answers`/question-id control
|
|
||||||
// any more. The lowering has no authored, non-editable
|
|
||||||
// binding value (`hidden` is not a prop any renderer
|
|
||||||
// reads — Soul's own probe found it rendered as a
|
|
||||||
// plain, editable, visible text box holding the raw
|
|
||||||
// id), so the server resolves the open question
|
|
||||||
// itself instead of trusting a client-supplied id at
|
|
||||||
// all (`runtime.rs::execute_world`'s `world.play`
|
|
||||||
// arm). PA.f170's guarantee now holds by an opaque
|
|
||||||
// per-question token rather than PA.f161's version
|
|
||||||
// comparison (see `play::PlayTurn::question_token`'s
|
|
||||||
// own doc comment for why a version alone cannot tell
|
|
||||||
// two questions in the same turn apart): the button's
|
|
||||||
// own `props.action` carries it DOM-invisibly, the
|
|
||||||
// way `props.action.command` already does — a real
|
|
||||||
// client spreads a button's own `action` fields
|
|
||||||
// straight into the payload beside `bindings`
|
|
||||||
// (`commandPayload`,
|
|
||||||
// `vendor/eve/packages/eve-browser-lowering/src/index.ts:2101`),
|
|
||||||
// never through a renderer that could show or edit
|
|
||||||
// it. `None` while no question is open: the button's
|
|
||||||
// own action then carries no token at all, matching a
|
|
||||||
// plain continue/opening, which needs none.
|
|
||||||
// PA.f179: `question.token` is `Option<String>` — a
|
|
||||||
// `None` here (a question open whose own token was,
|
|
||||||
// for whatever reason, never minted) serializes as a
|
|
||||||
// JSON `null`, which `runtime.rs`'s own
|
|
||||||
// `answer_token_admits` gate refuses unconditionally,
|
|
||||||
// the same as any other mismatch. It is never
|
|
||||||
// rendered as an empty string a forged answer could
|
|
||||||
// match.
|
|
||||||
let play_action = play
|
|
||||||
.and_then(|view| view.question.as_ref())
|
|
||||||
.map(|question| json!({"answerToken": question.token}))
|
|
||||||
.unwrap_or_else(|| json!({}));
|
|
||||||
children.extend([
|
|
||||||
json!({
|
|
||||||
"id":"world.play.text",
|
|
||||||
"kind":"control.input.textarea",
|
|
||||||
"props":{"label":"What do you do?","rows":3,"placeholder":"Write freely"},
|
|
||||||
"stateBindings":[local_draft("text", "string")],
|
|
||||||
"children":[]
|
|
||||||
}),
|
|
||||||
command_button(
|
|
||||||
"world.play",
|
|
||||||
"Play",
|
|
||||||
"world.play",
|
|
||||||
play_action,
|
|
||||||
&["text"],
|
|
||||||
),
|
|
||||||
]);
|
|
||||||
commands.push(command_descriptor(
|
|
||||||
"world.play",
|
|
||||||
"ghostlight.world_play.v0",
|
|
||||||
&["text"],
|
|
||||||
"PlayTable",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
children.push(command_button(
|
|
||||||
"app.auth.logout",
|
|
||||||
"Sign out",
|
|
||||||
"app.auth.logout",
|
|
||||||
json!({}),
|
|
||||||
&[],
|
|
||||||
));
|
|
||||||
commands.push(command_descriptor(
|
|
||||||
"app.auth.logout",
|
|
||||||
"ghostlight.app_logout.v2",
|
|
||||||
&[],
|
|
||||||
"AppSessionOwner",
|
|
||||||
));
|
|
||||||
Ok(surface_document(
|
|
||||||
version,
|
|
||||||
snapshot
|
|
||||||
.map(|world| world.title.as_str())
|
|
||||||
.unwrap_or("Ghostlight Dungeon"),
|
|
||||||
children,
|
|
||||||
commands,
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn validate_invocation(
|
|
||||||
invocation: &EveCommandInvocation,
|
|
||||||
expected_transport: &str,
|
|
||||||
) -> anyhow::Result<()> {
|
|
||||||
if invocation.schema != "gamecult.eve.command_invocation.v1"
|
|
||||||
|| invocation.provider_id != PROVIDER_ID
|
|
||||||
|| invocation.surface_id != SURFACE_ID
|
|
||||||
|| invocation.command_boundary != COMMAND_BOUNDARY
|
|
||||||
|| invocation.receipt_schema != COMMAND_RESULT_SCHEMA
|
|
||||||
{
|
|
||||||
bail!("invocation does not match the Ghostlight Eve boundary");
|
|
||||||
}
|
|
||||||
if invocation.operation.operation_id.trim().is_empty()
|
|
||||||
|| invocation
|
|
||||||
.operation
|
|
||||||
.idempotency_key
|
|
||||||
.as_deref()
|
|
||||||
.is_none_or(str::is_empty)
|
|
||||||
|| invocation
|
|
||||||
.operation
|
|
||||||
.schema_id
|
|
||||||
.as_deref()
|
|
||||||
.is_none_or(str::is_empty)
|
|
||||||
|| invocation.client_id.trim().is_empty()
|
|
||||||
|| invocation.issued_at.parse::<DateTime<Utc>>().is_err()
|
|
||||||
|| invocation.operation.route_hint.transport.as_deref() != Some(expected_transport)
|
|
||||||
{
|
|
||||||
bail!("invocation metadata is incomplete");
|
|
||||||
}
|
|
||||||
let expected = operation_schema(&invocation.operation.operation_id)
|
|
||||||
.context("Eve operation is not advertised by Ghostlight")?;
|
|
||||||
if invocation.operation.schema_id.as_deref() != Some(expected) {
|
|
||||||
bail!("operation payload schema does not match its command descriptor");
|
|
||||||
}
|
|
||||||
if invocation.payload.get("caller").is_some()
|
|
||||||
|| invocation.payload.get("caller_id").is_some()
|
|
||||||
|| invocation.payload.get("callerId").is_some()
|
|
||||||
{
|
|
||||||
bail!("payload may not supply caller authority");
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn operation_schema(operation: &str) -> Option<&'static str> {
|
|
||||||
Some(match operation {
|
|
||||||
"heimdall.auth.begin" => "heimdall.auth_begin_command.v1",
|
|
||||||
"heimdall.auth.complete" => "heimdall.auth_complete_command.v1",
|
|
||||||
"app.auth.logout" => "ghostlight.app_logout.v2",
|
|
||||||
"world.create" => "ghostlight.world_create.v4",
|
|
||||||
"world.approve" => "ghostlight.world_approve.v0",
|
|
||||||
"world.activate" => "ghostlight.world_activate.v0",
|
|
||||||
"world.advance_time" => "ghostlight.world_advance_time.v0",
|
|
||||||
"world.seed" => "ghostlight.world_seed.v1",
|
|
||||||
"world.play" => "ghostlight.world_play.v0",
|
|
||||||
_ => return None,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One command result in the shape `gamecult.eve.command_result.v1` actually
|
|
||||||
/// admits: `additionalProperties: false` over exactly `schema`, `receipt`,
|
|
||||||
/// `transientProjection`, `pluginPayload` and `draftDirective`, with the
|
|
||||||
/// per-command detail (state, message, source version, ids) inside the
|
|
||||||
/// receipt, which is `gamecult.eve.command_receipt.v1` and does allow its own
|
|
||||||
/// extra fields.
|
|
||||||
///
|
|
||||||
/// The browser validates this envelope before it looks at anything in it, so
|
|
||||||
/// a flat result is not a lenient dialect of the contract — it is rejected
|
|
||||||
/// whole, with the client reporting "invalid Eve command result: data must
|
|
||||||
/// not have additional properties" and no command of any kind completing.
|
|
||||||
pub(crate) fn command_result(
|
|
||||||
invocation: &EveCommandInvocation,
|
|
||||||
state: &str,
|
|
||||||
message: impl Into<String>,
|
|
||||||
source_version: Option<u64>,
|
|
||||||
plugin_payload: Option<Value>,
|
|
||||||
receipt_extra: Option<Value>,
|
|
||||||
) -> Value {
|
|
||||||
let message = message.into();
|
|
||||||
// A refusal is otherwise visible only to the browser that received it.
|
|
||||||
// The operator log gets the operation and the refusal's own message,
|
|
||||||
// never the payload.
|
|
||||||
if !matches!(state, "accepted" | "completed" | "pending") {
|
|
||||||
tracing::warn!(
|
|
||||||
operation = %invocation.operation.operation_id,
|
|
||||||
state,
|
|
||||||
message = %message,
|
|
||||||
"Eve command not accepted"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
let mut receipt = json!({
|
|
||||||
"schema":COMMAND_RECEIPT_SCHEMA,
|
|
||||||
"receiptId":Uuid::new_v4().to_string(),
|
|
||||||
"commandId":invocation.operation.idempotency_key.clone().unwrap_or_default(),
|
|
||||||
"command":invocation.operation.operation_id,
|
|
||||||
"state":state,
|
|
||||||
"ownerRepo":OWNER_REPO,
|
|
||||||
"authority":PROVIDER_ID,
|
|
||||||
"providerId":PROVIDER_ID,
|
|
||||||
"surfaceId":SURFACE_ID,
|
|
||||||
"message":message,
|
|
||||||
// The contract requires a source version and refuses a null one. A
|
|
||||||
// command that reports no version reports the surface it was decided
|
|
||||||
// against, which is 0 before any world exists.
|
|
||||||
"sourceVersion":source_version.unwrap_or(0),
|
|
||||||
"issuedAtUtc":Utc::now().to_rfc3339()
|
|
||||||
});
|
|
||||||
if let (Some(map), Some(extra)) = (receipt.as_object_mut(), receipt_extra) {
|
|
||||||
if let Some(extra) = extra.as_object() {
|
|
||||||
for (key, value) in extra {
|
|
||||||
map.insert(key.clone(), value.clone());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let mut result = json!({
|
|
||||||
"schema":COMMAND_RESULT_SCHEMA,
|
|
||||||
"receipt":receipt
|
|
||||||
});
|
|
||||||
if let (Some(map), Some(payload)) = (result.as_object_mut(), plugin_payload) {
|
|
||||||
map.insert("pluginPayload".into(), payload);
|
|
||||||
}
|
|
||||||
result
|
|
||||||
}
|
|
||||||
|
|
||||||
fn surface_document(
|
|
||||||
version: u64,
|
|
||||||
title: &str,
|
|
||||||
children: Vec<Value>,
|
|
||||||
commands: Vec<Value>,
|
|
||||||
) -> Value {
|
|
||||||
json!({
|
|
||||||
"type":"surface-state",
|
|
||||||
"schema":"gamecult.eve.surface.v1",
|
|
||||||
"providerId":PROVIDER_ID,
|
|
||||||
"providerKind":"narrative.simulation",
|
|
||||||
"title":title,
|
|
||||||
// The one meaning `routeHint.sourceVersion` and the kernel's
|
|
||||||
// compare-and-swap require of it (PA.f148/PA.f160): `surface_version`
|
|
||||||
// alone. The play row's own revision has no wire reader (PA.f165)
|
|
||||||
// and is never carried here.
|
|
||||||
"version":version,
|
|
||||||
"updatedAtUtc":Utc::now().to_rfc3339(),
|
|
||||||
"surface":{
|
|
||||||
"id":SURFACE_ID,
|
|
||||||
"root":{"id":"ghostlight.root","kind":"surface","props":{},"children":children},
|
|
||||||
"styles":{"tokens":{
|
|
||||||
"colorBackground":"#0c1110",
|
|
||||||
"colorPanel":"#17201d",
|
|
||||||
"colorText":"#e8e1cf",
|
|
||||||
"colorMuted":"#9aa69f",
|
|
||||||
"colorAccent":"#d49b58"
|
|
||||||
}}
|
|
||||||
},
|
|
||||||
"commands":commands
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn command_button(id: &str, label: &str, command: &str, action: Value, bindings: &[&str]) -> Value {
|
|
||||||
let mut action = action.as_object().cloned().unwrap_or_default();
|
|
||||||
action.insert("command".into(), Value::String(command.into()));
|
|
||||||
json!({
|
|
||||||
"id":id,
|
|
||||||
"kind":"control.button",
|
|
||||||
"props":{"label":label,"command":command,"action":action,"captureBindings":bindings},
|
|
||||||
"children":[]
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn command_descriptor(command: &str, schema: &str, bindings: &[&str], authority: &str) -> Value {
|
|
||||||
json!({
|
|
||||||
"schema":"gamecult.eve.command.v1",
|
|
||||||
"command":command,
|
|
||||||
"payloadSchema":schema,
|
|
||||||
"captureBindings":bindings,
|
|
||||||
"transport":"https-json",
|
|
||||||
"authority":authority
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A `captureBindings` entry the vendored browser lowering
|
|
||||||
/// (`@gamecult/eve-browser-lowering`, `EveStateBindingDescriptor`) actually
|
|
||||||
/// resolves, field-for-field the same shape its own test suite
|
|
||||||
/// (`test/host-isolation.test.mjs`) builds for its own `composer.message`
|
|
||||||
/// local-draft binding: `targetProp`, `pointerId`, `sourceId`, `schemaId`,
|
|
||||||
/// `routeKind`, `bindingName`, `valueKind`, `accessMode`, `authority`.
|
|
||||||
///
|
|
||||||
/// Two fields are load-bearing. `bindingName` must equal `key`, since `key`
|
|
||||||
/// is also the exact string Dungeon's own `captureBindings` array and
|
|
||||||
/// `command_descriptor` advertise — `findAuthoredBindingValue` and
|
|
||||||
/// `editableBindingContext` both match a binding by this field (falling back
|
|
||||||
/// to `pointerId`, then the control's own node id, only when it is absent).
|
|
||||||
/// `accessMode` must stay `"local-draft"`: `editableBindingContext`
|
|
||||||
/// (`src/index.ts:2198`) defaults an absent `accessMode` to `"read"` whenever
|
|
||||||
/// a binding is present at all, and a `"read"` control is disabled
|
|
||||||
/// (`:2205`) — an editable field with no `accessMode` here would render
|
|
||||||
/// disabled, not merely miscaptured. The remaining fields
|
|
||||||
/// (`targetProp`, `pointerId`, `sourceId`, `schemaId`, `routeKind`,
|
|
||||||
/// `valueKind`, `authority`) carry no runtime behavior in the current
|
|
||||||
/// lowering (grep confirms `valueKind` is read nowhere), but are still worth
|
|
||||||
/// stating correctly rather than leaving absent.
|
|
||||||
///
|
|
||||||
/// `value_kind` must be one of the lowering's own `valueKind` union
|
|
||||||
/// (`"string" | "number" | "boolean" | "choice" | "string-list"`); Dungeon's
|
|
||||||
/// own JSON-textarea fields (`targets`, `jurisdictions`, `lens_weights`) are,
|
|
||||||
/// client-side, plain text controls like any other — there is no JSON
|
|
||||||
/// `valueKind` — so callers pass `"string"` for those too, and the server
|
|
||||||
/// side parses the captured text as JSON (`deserialize_json_capture` in
|
|
||||||
/// `runtime.rs`).
|
|
||||||
fn local_draft(key: &str, value_kind: &str) -> Value {
|
|
||||||
json!({
|
|
||||||
"targetProp":"value",
|
|
||||||
"pointerId":format!("ghostlight.local.{key}"),
|
|
||||||
"sourceId":"eve.browser.local",
|
|
||||||
"schemaId":"gamecult.eve.local_draft.v1",
|
|
||||||
"routeKind":"in-process",
|
|
||||||
"bindingName":key,
|
|
||||||
"valueKind":value_kind,
|
|
||||||
"accessMode":"local-draft",
|
|
||||||
"authority":"eve.browser"
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn short_principal(principal: &str) -> String {
|
|
||||||
principal.chars().take(20).collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
fn invocation(operation: &str, schema: &str, payload: Value) -> EveCommandInvocation {
|
|
||||||
EveCommandInvocation {
|
|
||||||
schema: "gamecult.eve.command_invocation.v1".into(),
|
|
||||||
provider_id: PROVIDER_ID.into(),
|
|
||||||
surface_id: SURFACE_ID.into(),
|
|
||||||
operation: EveOperation {
|
|
||||||
operation_id: operation.into(),
|
|
||||||
schema_id: Some(schema.into()),
|
|
||||||
idempotency_key: Some(uuid::Uuid::new_v4().to_string()),
|
|
||||||
route_hint: EveRouteHint {
|
|
||||||
source_version: Some(0),
|
|
||||||
transport: Some("https-json".into()),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
payload,
|
|
||||||
issued_at: Utc::now().to_rfc3339(),
|
|
||||||
client_id: "fixture".into(),
|
|
||||||
command_boundary: COMMAND_BOUNDARY.into(),
|
|
||||||
receipt_schema: COMMAND_RESULT_SCHEMA.into(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn anonymous_surface_advertises_only_authentication() {
|
|
||||||
let surface = anonymous_surface();
|
|
||||||
let commands = surface["commands"].as_array().unwrap();
|
|
||||||
assert_eq!(commands.len(), 1);
|
|
||||||
assert_eq!(commands[0]["command"], "heimdall.auth.begin");
|
|
||||||
assert_eq!(surface["version"], 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn empty_authenticated_surface_has_create_without_session_zero() {
|
|
||||||
let surface = authenticated_surface("sha256:owner", None, None).unwrap();
|
|
||||||
let encoded = serde_json::to_string(&surface).unwrap();
|
|
||||||
assert!(encoded.contains("world.create"));
|
|
||||||
assert!(encoded.contains("narrative_persona_label"));
|
|
||||||
assert!(encoded.contains("operational_agent_label"));
|
|
||||||
assert!(!encoded.contains("session_zero"));
|
|
||||||
assert!(!encoded.contains("campaign"));
|
|
||||||
assert_eq!(surface["version"], 0);
|
|
||||||
|
|
||||||
// The lens control's default is Dungeon's uniform policy, every stock
|
|
||||||
// lens named, and it decodes as the weights the payload will carry.
|
|
||||||
fn find<'a>(node: &'a Value, id: &str) -> Option<&'a Value> {
|
|
||||||
if node["id"] == id {
|
|
||||||
return Some(node);
|
|
||||||
}
|
|
||||||
node.as_object()?
|
|
||||||
.values()
|
|
||||||
.flat_map(|value| match value {
|
|
||||||
Value::Array(items) => items.iter().collect::<Vec<_>>(),
|
|
||||||
other => vec![other],
|
|
||||||
})
|
|
||||||
.find_map(|child| find(child, id))
|
|
||||||
}
|
|
||||||
let control = find(&surface, "world.create.lens_weights").expect("a lens weights control");
|
|
||||||
let default = control["props"]["value"].as_str().expect("a default value");
|
|
||||||
let decoded: ghostlight::LensWeights = serde_json::from_str(default).unwrap();
|
|
||||||
assert_eq!(decoded, crate::runtime::uniform_lens_weights());
|
|
||||||
assert_eq!(decoded.iter().count(), ghostlight::Lens::ALL.len());
|
|
||||||
assert!(decoded.iter().all(|(_, weight)| weight == 1));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `world.play`'s own operation id resolves to its schema through
|
|
||||||
/// `operation_schema`, so an invocation whose payload matches it
|
|
||||||
/// validates, and a payload that tries to claim authority is refused —
|
|
||||||
/// the same claim this test once made for the now-deleted speak
|
|
||||||
/// operation, PA.f146's own precedent (Cut 8b's schema existed here
|
|
||||||
/// before Cut 9 published `world.play`'s own descriptor and button,
|
|
||||||
/// below).
|
|
||||||
#[test]
|
|
||||||
fn payload_cannot_claim_authority() {
|
|
||||||
assert_eq!(operation_schema("world.play"), Some("ghostlight.world_play.v0"));
|
|
||||||
|
|
||||||
let bound = invocation(
|
|
||||||
"world.play",
|
|
||||||
"ghostlight.world_play.v0",
|
|
||||||
json!({"text":"I look around.", "answers": null}),
|
|
||||||
);
|
|
||||||
assert!(validate_invocation(&bound, "https-json").is_ok());
|
|
||||||
|
|
||||||
let forged = invocation(
|
|
||||||
"world.play",
|
|
||||||
"ghostlight.world_play.v0",
|
|
||||||
json!({"text":"I look around.", "answers": null, "caller":"owner"}),
|
|
||||||
);
|
|
||||||
assert!(validate_invocation(&forged, "https-json").is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn invocation_metadata_rejects_legacy_authority_extensions() {
|
|
||||||
let exact = invocation(
|
|
||||||
"world.play",
|
|
||||||
"ghostlight.world_play.v0",
|
|
||||||
json!({"text":"I look around.", "answers": null}),
|
|
||||||
);
|
|
||||||
let mut outer = serde_json::to_value(&exact).unwrap();
|
|
||||||
outer["callerId"] = json!("legacy-owner");
|
|
||||||
assert!(serde_json::from_value::<EveCommandInvocation>(outer).is_err());
|
|
||||||
|
|
||||||
let mut route = serde_json::to_value(&exact).unwrap();
|
|
||||||
route["operation"]["routeHint"]["caller"] = json!("legacy-owner");
|
|
||||||
assert!(serde_json::from_value::<EveCommandInvocation>(route).is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn removed_operation_is_unknown() {
|
|
||||||
assert!(operation_schema("session_zero.begin").is_none());
|
|
||||||
assert!(operation_schema("world.assess").is_none());
|
|
||||||
assert!(operation_schema("governance.time.propose").is_none());
|
|
||||||
assert!(operation_schema("world.speak").is_none());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,131 +0,0 @@
|
||||||
{
|
|
||||||
"schema": "ghostlight.eve_client_bridge_fixture.v1",
|
|
||||||
"steps": [
|
|
||||||
{
|
|
||||||
"intent": {
|
|
||||||
"clientId": "eve.bridge.test",
|
|
||||||
"commandBoundary": "ghostlight.eve.commands",
|
|
||||||
"issuedAt": "2026-09-22T23:30:03.348Z",
|
|
||||||
"operation": {
|
|
||||||
"idempotencyKey": "0af70fc4-d2bf-4f9b-9914-696a27580065",
|
|
||||||
"operationId": "world.create",
|
|
||||||
"routeHint": {
|
|
||||||
"sourceVersion": 0,
|
|
||||||
"transport": "https-json"
|
|
||||||
},
|
|
||||||
"schemaId": "ghostlight.world_create.v4"
|
|
||||||
},
|
|
||||||
"payload": {
|
|
||||||
"bindings": {
|
|
||||||
"brief": "A world captured for the committed Eve client bridge fixture.",
|
|
||||||
"jurisdictions": "[]",
|
|
||||||
"lens_weights": "{\"patina\":1,\"charter\":1,\"ledger\":1,\"hearth\":1,\"tangle\":1,\"veil\":1,\"ember\":1,\"numen\":1}",
|
|
||||||
"subject_label": "The Fixture Operator",
|
|
||||||
"targets": "{}",
|
|
||||||
"title": "Bridge Fixture World"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"providerId": "gamecult.ghostlight.dungeon",
|
|
||||||
"receiptSchema": "gamecult.eve.command_result.v1",
|
|
||||||
"schema": "gamecult.eve.command_invocation.v1",
|
|
||||||
"surfaceId": "ghostlight.play"
|
|
||||||
},
|
|
||||||
"label": "world.create"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"intent": {
|
|
||||||
"clientId": "eve.bridge.test",
|
|
||||||
"commandBoundary": "ghostlight.eve.commands",
|
|
||||||
"issuedAt": "2026-09-22T23:30:05.143Z",
|
|
||||||
"operation": {
|
|
||||||
"idempotencyKey": "99503a87-9e15-45b7-8776-765a8dc4216b",
|
|
||||||
"operationId": "world.approve",
|
|
||||||
"routeHint": {
|
|
||||||
"sourceVersion": 1,
|
|
||||||
"transport": "https-json"
|
|
||||||
},
|
|
||||||
"schemaId": "ghostlight.world_approve.v0"
|
|
||||||
},
|
|
||||||
"payload": {},
|
|
||||||
"providerId": "gamecult.ghostlight.dungeon",
|
|
||||||
"receiptSchema": "gamecult.eve.command_result.v1",
|
|
||||||
"schema": "gamecult.eve.command_invocation.v1",
|
|
||||||
"surfaceId": "ghostlight.play"
|
|
||||||
},
|
|
||||||
"label": "world.approve"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"intent": {
|
|
||||||
"clientId": "eve.bridge.test",
|
|
||||||
"commandBoundary": "ghostlight.eve.commands",
|
|
||||||
"issuedAt": "2026-09-22T23:30:07.195Z",
|
|
||||||
"operation": {
|
|
||||||
"idempotencyKey": "1d6a441e-f173-41af-a798-a9123039d5e0",
|
|
||||||
"operationId": "world.seed",
|
|
||||||
"routeHint": {
|
|
||||||
"sourceVersion": 2,
|
|
||||||
"transport": "https-json"
|
|
||||||
},
|
|
||||||
"schemaId": "ghostlight.world_seed.v1"
|
|
||||||
},
|
|
||||||
"payload": {
|
|
||||||
"bindings": {}
|
|
||||||
},
|
|
||||||
"providerId": "gamecult.ghostlight.dungeon",
|
|
||||||
"receiptSchema": "gamecult.eve.command_result.v1",
|
|
||||||
"schema": "gamecult.eve.command_invocation.v1",
|
|
||||||
"surfaceId": "ghostlight.play"
|
|
||||||
},
|
|
||||||
"label": "world.seed"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"intent": {
|
|
||||||
"clientId": "eve.bridge.test",
|
|
||||||
"commandBoundary": "ghostlight.eve.commands",
|
|
||||||
"issuedAt": "2026-09-22T23:30:09.010Z",
|
|
||||||
"operation": {
|
|
||||||
"idempotencyKey": "20d01b36-cdfa-4e59-b5f3-31be54d94bc6",
|
|
||||||
"operationId": "world.activate",
|
|
||||||
"routeHint": {
|
|
||||||
"sourceVersion": 2,
|
|
||||||
"transport": "https-json"
|
|
||||||
},
|
|
||||||
"schemaId": "ghostlight.world_activate.v0"
|
|
||||||
},
|
|
||||||
"payload": {},
|
|
||||||
"providerId": "gamecult.ghostlight.dungeon",
|
|
||||||
"receiptSchema": "gamecult.eve.command_result.v1",
|
|
||||||
"schema": "gamecult.eve.command_invocation.v1",
|
|
||||||
"surfaceId": "ghostlight.play"
|
|
||||||
},
|
|
||||||
"label": "world.activate"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"intent": {
|
|
||||||
"clientId": "eve.bridge.test",
|
|
||||||
"commandBoundary": "ghostlight.eve.commands",
|
|
||||||
"issuedAt": "2026-09-22T23:30:11.040Z",
|
|
||||||
"operation": {
|
|
||||||
"idempotencyKey": "2301df6e-397b-4d5b-afa3-ef965e57b49a",
|
|
||||||
"operationId": "world.play",
|
|
||||||
"routeHint": {
|
|
||||||
"sourceVersion": 3,
|
|
||||||
"transport": "https-json"
|
|
||||||
},
|
|
||||||
"schemaId": "ghostlight.world_play.v0"
|
|
||||||
},
|
|
||||||
"payload": {
|
|
||||||
"bindings": {
|
|
||||||
"text": "The new owner looks around."
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"providerId": "gamecult.ghostlight.dungeon",
|
|
||||||
"receiptSchema": "gamecult.eve.command_result.v1",
|
|
||||||
"schema": "gamecult.eve.command_invocation.v1",
|
|
||||||
"surfaceId": "ghostlight.play"
|
|
||||||
},
|
|
||||||
"label": "world.play"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"vendorEveSubmoduleRevision": "672c0c1e9fc828b63752345385727b06c50491d0"
|
|
||||||
}
|
|
||||||
|
|
@ -15,7 +15,10 @@ use cultnet_rs::{
|
||||||
CultNetRudpSocketTransportOptions,
|
CultNetRudpSocketTransportOptions,
|
||||||
};
|
};
|
||||||
use hmac::{Hmac, Mac};
|
use hmac::{Hmac, Mac};
|
||||||
use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode, decode_header, jwk::JwkSet};
|
use jsonwebtoken::{
|
||||||
|
Algorithm, DecodingKey, Validation, decode, decode_header,
|
||||||
|
jwk::{Jwk, JwkSet},
|
||||||
|
};
|
||||||
use rand::RngCore;
|
use rand::RngCore;
|
||||||
use reqwest::Client;
|
use reqwest::Client;
|
||||||
use serde::{Deserialize, Serialize, de::DeserializeOwned};
|
use serde::{Deserialize, Serialize, de::DeserializeOwned};
|
||||||
|
|
@ -23,6 +26,7 @@ use sha2::{Digest, Sha256};
|
||||||
use std::{
|
use std::{
|
||||||
net::{SocketAddr, UdpSocket},
|
net::{SocketAddr, UdpSocket},
|
||||||
path::PathBuf,
|
path::PathBuf,
|
||||||
|
sync::{Arc, Mutex as StdMutex},
|
||||||
time::{Duration, Instant},
|
time::{Duration, Instant},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -30,37 +34,237 @@ const APP_SLUG: &str = "ghostlight";
|
||||||
const PRIVATE_SERVICE: &str = "heimdall.private.commands";
|
const PRIVATE_SERVICE: &str = "heimdall.private.commands";
|
||||||
const PRIVATE_ENVELOPE_SCHEMA: &str = "heimdall.private_command_envelope.v1";
|
const PRIVATE_ENVELOPE_SCHEMA: &str = "heimdall.private_command_envelope.v1";
|
||||||
|
|
||||||
|
/// Heimdall answered a private command with status denied. Distinct from a
|
||||||
|
/// transport failure so the refresh loop never reads a message string.
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
#[error("Heimdall denied the private command: {diagnostics}")]
|
||||||
|
pub(crate) struct HeimdallDenied {
|
||||||
|
pub(crate) diagnostics: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Heimdall's signing keys could not be fetched, so a receipt could not be
|
||||||
|
/// judged either way. Distinct from a receipt that positively fails
|
||||||
|
/// verification: the refresh loop keeps the receipt for this and revokes for
|
||||||
|
/// that. It carries an error class and never the fetch error itself, whose
|
||||||
|
/// text names the key-set URL: an error never echoes an input value.
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
#[error("Heimdall signing keys unavailable: the key-set fetch {class}")]
|
||||||
|
pub(crate) struct VerificationUnavailable {
|
||||||
|
class: &'static str,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VerificationUnavailable {
|
||||||
|
fn of_fetch(error: &reqwest::Error) -> Self {
|
||||||
|
let class = if error.is_timeout() {
|
||||||
|
"timed out"
|
||||||
|
} else if error.is_connect() {
|
||||||
|
"could not connect"
|
||||||
|
} else if error.is_status() {
|
||||||
|
"returned an error status"
|
||||||
|
} else if error.is_decode() {
|
||||||
|
"returned an unreadable key set"
|
||||||
|
} else {
|
||||||
|
"failed"
|
||||||
|
};
|
||||||
|
Self { class }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
pub(crate) fn new(class: &'static str) -> Self {
|
||||||
|
Self { class }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How long a fetched signing-key set is trusted before it is fetched again.
|
||||||
|
const JWKS_TTL: Duration = Duration::from_secs(300);
|
||||||
|
|
||||||
|
/// The last fetched signing-key set and when it was fetched.
|
||||||
|
#[derive(Default)]
|
||||||
|
pub(crate) struct JwksCache {
|
||||||
|
fetched: Option<(Instant, JwkSet)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl JwksCache {
|
||||||
|
/// The key published under `kid`, if the cached set is still fresh and
|
||||||
|
/// holds it. A miss on a fresh set still refetches, so a rotated key is
|
||||||
|
/// found.
|
||||||
|
pub(crate) fn key(&self, kid: &str, now: Instant) -> Option<Jwk> {
|
||||||
|
let (fetched_at, set) = self.fetched.as_ref()?;
|
||||||
|
if now.saturating_duration_since(*fetched_at) >= JWKS_TTL {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
set.find(kid).cloned()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn store(&mut self, set: JwkSet, now: Instant) {
|
||||||
|
self.fetched = Some((now, set));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The two Heimdall calls the refresh loop makes, as a port so a scripted
|
||||||
|
/// Heimdall can stand in for the real one.
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
pub(crate) trait SessionRefresher {
|
||||||
|
async fn refresh(
|
||||||
|
&self,
|
||||||
|
refresh_token: &str,
|
||||||
|
idempotency_key: &str,
|
||||||
|
) -> anyhow::Result<AuthCompletionReceipt>;
|
||||||
|
|
||||||
|
async fn verify_refresh(
|
||||||
|
&self,
|
||||||
|
completion: AuthCompletionReceipt,
|
||||||
|
) -> anyhow::Result<VerifiedSessionRefresh>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl SessionRefresher for HeimdallClient {
|
||||||
|
async fn refresh(
|
||||||
|
&self,
|
||||||
|
refresh_token: &str,
|
||||||
|
idempotency_key: &str,
|
||||||
|
) -> anyhow::Result<AuthCompletionReceipt> {
|
||||||
|
HeimdallClient::refresh(self, refresh_token, idempotency_key).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn verify_refresh(
|
||||||
|
&self,
|
||||||
|
completion: AuthCompletionReceipt,
|
||||||
|
) -> anyhow::Result<VerifiedSessionRefresh> {
|
||||||
|
HeimdallClient::verify_refresh(self, completion).await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A sign-in provider Heimdall may be asked to authenticate with. The Dungeon
|
||||||
|
/// owns which of them it offers; Heimdall's app profile owns which it accepts.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub(crate) enum AuthProvider {
|
||||||
|
Google,
|
||||||
|
Discord,
|
||||||
|
Twitch,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AuthProvider {
|
||||||
|
pub(crate) fn parse(name: &str) -> Option<Self> {
|
||||||
|
match name {
|
||||||
|
"google" => Some(Self::Google),
|
||||||
|
"discord" => Some(Self::Discord),
|
||||||
|
"twitch" => Some(Self::Twitch),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn as_str(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::Google => "google",
|
||||||
|
Self::Discord => "discord",
|
||||||
|
Self::Twitch => "twitch",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The offered set from `GHOSTLIGHT_AUTH_PROVIDERS`, a comma list. An
|
||||||
|
/// unnamed provider is a startup error, not a silent drop.
|
||||||
|
fn set_from(value: &str) -> anyhow::Result<Vec<Self>> {
|
||||||
|
let mut set = Vec::new();
|
||||||
|
for name in value.split(',').map(str::trim).filter(|name| !name.is_empty()) {
|
||||||
|
let provider = Self::parse(name)
|
||||||
|
.with_context(|| format!("GHOSTLIGHT_AUTH_PROVIDERS names an unknown provider {name:?}"))?;
|
||||||
|
if !set.contains(&provider) {
|
||||||
|
set.push(provider);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
anyhow::ensure!(!set.is_empty(), "GHOSTLIGHT_AUTH_PROVIDERS names no provider");
|
||||||
|
Ok(set)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The sign-in half of Heimdall the HTTP handlers use, as a port so a scripted
|
||||||
|
/// Heimdall can stand in for the real one. The refresh loop's half is the
|
||||||
|
/// supertrait.
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
pub(crate) trait HeimdallPort: SessionRefresher + Send + Sync {
|
||||||
|
/// The provider named, if the Dungeon offers it.
|
||||||
|
fn offered(&self, name: &str) -> Option<AuthProvider>;
|
||||||
|
|
||||||
|
async fn begin(
|
||||||
|
&self,
|
||||||
|
provider: AuthProvider,
|
||||||
|
grant: bool,
|
||||||
|
idempotency_key: &str,
|
||||||
|
) -> anyhow::Result<AuthBeginReceipt>;
|
||||||
|
|
||||||
|
async fn complete(
|
||||||
|
&self,
|
||||||
|
handle: &str,
|
||||||
|
idempotency_key: &str,
|
||||||
|
) -> anyhow::Result<AuthCompletionReceipt>;
|
||||||
|
|
||||||
|
async fn verify_completion(
|
||||||
|
&self,
|
||||||
|
completion: AuthCompletionReceipt,
|
||||||
|
) -> anyhow::Result<VerifiedSessionAdmission>;
|
||||||
|
|
||||||
|
async fn logout(
|
||||||
|
&self,
|
||||||
|
refresh_token: &str,
|
||||||
|
idempotency_key: &str,
|
||||||
|
) -> anyhow::Result<AuthLogoutReceipt>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl HeimdallPort for HeimdallClient {
|
||||||
|
fn offered(&self, name: &str) -> Option<AuthProvider> {
|
||||||
|
AuthProvider::parse(name).filter(|provider| self.providers.contains(provider))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn begin(
|
||||||
|
&self,
|
||||||
|
provider: AuthProvider,
|
||||||
|
grant: bool,
|
||||||
|
idempotency_key: &str,
|
||||||
|
) -> anyhow::Result<AuthBeginReceipt> {
|
||||||
|
HeimdallClient::begin(self, provider, grant, idempotency_key).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn complete(
|
||||||
|
&self,
|
||||||
|
handle: &str,
|
||||||
|
idempotency_key: &str,
|
||||||
|
) -> anyhow::Result<AuthCompletionReceipt> {
|
||||||
|
HeimdallClient::complete(self, handle, idempotency_key).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn verify_completion(
|
||||||
|
&self,
|
||||||
|
completion: AuthCompletionReceipt,
|
||||||
|
) -> anyhow::Result<VerifiedSessionAdmission> {
|
||||||
|
HeimdallClient::verify_completion(self, completion).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn logout(
|
||||||
|
&self,
|
||||||
|
refresh_token: &str,
|
||||||
|
idempotency_key: &str,
|
||||||
|
) -> anyhow::Result<AuthLogoutReceipt> {
|
||||||
|
HeimdallClient::logout(self, refresh_token, idempotency_key).await
|
||||||
|
}
|
||||||
|
}
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct HeimdallClient {
|
pub struct HeimdallClient {
|
||||||
http: Client,
|
http: Client,
|
||||||
issuer: String,
|
issuer: String,
|
||||||
public_app_url: String,
|
public_app_url: String,
|
||||||
discord_guild_id: String,
|
providers: Vec<AuthProvider>,
|
||||||
discord_role_id: String,
|
|
||||||
boundary_locator: HeimdallBoundaryLocator,
|
boundary_locator: HeimdallBoundaryLocator,
|
||||||
runtime_id: String,
|
runtime_id: String,
|
||||||
shared_secret: String,
|
shared_secret: String,
|
||||||
}
|
jwks: Arc<StdMutex<JwksCache>>,
|
||||||
|
|
||||||
/// Idunn's projection of a managed Heimdall dependency, when Heimdall is a
|
|
||||||
/// v2-managed target (it is not, as of this cut: every v2 deploy of it has
|
|
||||||
/// failed and it still runs as the legacy `heimdall.service`, so
|
|
||||||
/// `runtime.rs` always passes `None` here). Not an Idunn dependency in
|
|
||||||
/// `deployment/idunn/recipe.toml` right now, but the type stays owned here
|
|
||||||
/// so `require_expected_heimdall_boundary` below can resume checking a
|
|
||||||
/// discovered boundary against it the moment Heimdall returns as a managed
|
|
||||||
/// dependency, without re-deriving this shape from scratch.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub(crate) struct HeimdallDependencyBinding {
|
|
||||||
pub(crate) provider_id: String,
|
|
||||||
pub(crate) endpoint: SocketAddr,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
enum HeimdallBoundaryLocator {
|
enum HeimdallBoundaryLocator {
|
||||||
Odin {
|
Odin {
|
||||||
endpoint: SocketAddr,
|
endpoint: SocketAddr,
|
||||||
expected: Option<HeimdallDependencyBinding>,
|
|
||||||
},
|
},
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
Fixed(ResolvedHeimdallBoundary),
|
Fixed(ResolvedHeimdallBoundary),
|
||||||
|
|
@ -142,7 +346,11 @@ struct BeginCommand<'a> {
|
||||||
provider: &'a str,
|
provider: &'a str,
|
||||||
mode: &'a str,
|
mode: &'a str,
|
||||||
return_to: &'a str,
|
return_to: &'a str,
|
||||||
entitlement_policy: DiscordRolePolicy<'a>,
|
/// `"invite"` when the browser presented an invite the catalog holds live:
|
||||||
|
/// it lets Heimdall mint an auth account for a first-time identity. The
|
||||||
|
/// Dungeon's catalog, not Heimdall, decides who is admitted.
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
first_login_grant: Option<&'static str>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize)]
|
#[derive(Serialize)]
|
||||||
|
|
@ -150,7 +358,6 @@ struct BeginCommand<'a> {
|
||||||
struct RefreshCommand<'a> {
|
struct RefreshCommand<'a> {
|
||||||
schema: &'static str,
|
schema: &'static str,
|
||||||
refresh_token: &'a str,
|
refresh_token: &'a str,
|
||||||
entitlement_policy: DiscordRolePolicy<'a>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize)]
|
#[derive(Serialize)]
|
||||||
|
|
@ -160,14 +367,6 @@ struct LogoutCommand<'a> {
|
||||||
refresh_token: &'a str,
|
refresh_token: &'a str,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
struct DiscordRolePolicy<'a> {
|
|
||||||
kind: &'a str,
|
|
||||||
guild_id: &'a str,
|
|
||||||
allowed_role_ids: [&'a str; 1],
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize)]
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct AuthBeginReceipt {
|
pub struct AuthBeginReceipt {
|
||||||
|
|
@ -184,7 +383,7 @@ pub struct AuthNavigation {
|
||||||
pub allowed_origins: Vec<String>,
|
pub allowed_origins: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Clone, Debug, Deserialize)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct AuthCompletionReceipt {
|
pub struct AuthCompletionReceipt {
|
||||||
pub status: String,
|
pub status: String,
|
||||||
|
|
@ -199,12 +398,12 @@ pub struct AuthCompletionReceipt {
|
||||||
pub shared_capabilities: Vec<String>,
|
pub shared_capabilities: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Clone, Debug, Deserialize)]
|
||||||
pub struct AccountSummary {
|
pub struct AccountSummary {
|
||||||
pub id: String,
|
pub id: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Clone, Debug, Deserialize)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct HeimdallSession {
|
pub struct HeimdallSession {
|
||||||
pub account_id: String,
|
pub account_id: String,
|
||||||
|
|
@ -214,7 +413,7 @@ pub struct HeimdallSession {
|
||||||
pub expires_at: String,
|
pub expires_at: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Clone, Debug, Deserialize)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct RefreshSummary {
|
pub struct RefreshSummary {
|
||||||
pub expires_at: String,
|
pub expires_at: String,
|
||||||
|
|
@ -325,12 +524,30 @@ impl VerifiedSessionAdmission {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
impl VerifiedSessionRefresh {
|
||||||
|
pub(crate) fn fixture(
|
||||||
|
account_id: impl Into<String>,
|
||||||
|
heimdall_session_id: impl Into<String>,
|
||||||
|
access_revision: u64,
|
||||||
|
access_expires_at: DateTime<Utc>,
|
||||||
|
refresh_expires_at: DateTime<Utc>,
|
||||||
|
refresh_claim: impl Into<String>,
|
||||||
|
) -> Self {
|
||||||
|
Self(VerifiedSessionMaterial {
|
||||||
|
account_id: account_id.into(),
|
||||||
|
heimdall_session_id: heimdall_session_id.into(),
|
||||||
|
access_revision,
|
||||||
|
capabilities: vec!["app_access".into()],
|
||||||
|
access_expires_at,
|
||||||
|
refresh_expires_at,
|
||||||
|
refresh_claim: refresh_claim.into(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl HeimdallClient {
|
impl HeimdallClient {
|
||||||
pub fn from_env(
|
pub fn from_env(runtime_id: &str, odin_endpoint: SocketAddr) -> anyhow::Result<Self> {
|
||||||
runtime_id: &str,
|
|
||||||
odin_endpoint: SocketAddr,
|
|
||||||
expected: Option<HeimdallDependencyBinding>,
|
|
||||||
) -> anyhow::Result<Self> {
|
|
||||||
if runtime_id.is_empty() || runtime_id.trim() != runtime_id {
|
if runtime_id.is_empty() || runtime_id.trim() != runtime_id {
|
||||||
bail!("Ghostlight runtime identity is not canonical");
|
bail!("Ghostlight runtime identity is not canonical");
|
||||||
}
|
}
|
||||||
|
|
@ -344,6 +561,9 @@ impl HeimdallClient {
|
||||||
if shared_secret.is_empty() {
|
if shared_secret.is_empty() {
|
||||||
bail!("Ghostlight's Heimdall app secret is empty");
|
bail!("Ghostlight's Heimdall app secret is empty");
|
||||||
}
|
}
|
||||||
|
let providers = AuthProvider::set_from(
|
||||||
|
&std::env::var("GHOSTLIGHT_AUTH_PROVIDERS").unwrap_or_else(|_| "discord".into()),
|
||||||
|
)?;
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
http: Client::builder().timeout(Duration::from_secs(10)).build()?,
|
http: Client::builder().timeout(Duration::from_secs(10)).build()?,
|
||||||
issuer: std::env::var("GHOSTLIGHT_HEIMDALL_BASE_URL")
|
issuer: std::env::var("GHOSTLIGHT_HEIMDALL_BASE_URL")
|
||||||
|
|
@ -352,14 +572,13 @@ impl HeimdallClient {
|
||||||
.into(),
|
.into(),
|
||||||
public_app_url: std::env::var("GHOSTLIGHT_PUBLIC_APP_URL")
|
public_app_url: std::env::var("GHOSTLIGHT_PUBLIC_APP_URL")
|
||||||
.unwrap_or_else(|_| "https://yggdrasil.gamecult.org/ghostlight/".into()),
|
.unwrap_or_else(|_| "https://yggdrasil.gamecult.org/ghostlight/".into()),
|
||||||
discord_guild_id: required_env("GHOSTLIGHT_DISCORD_GUILD_ID")?,
|
providers,
|
||||||
discord_role_id: required_env("GHOSTLIGHT_DISCORD_ROLE_ID")?,
|
|
||||||
boundary_locator: HeimdallBoundaryLocator::Odin {
|
boundary_locator: HeimdallBoundaryLocator::Odin {
|
||||||
endpoint: odin_endpoint,
|
endpoint: odin_endpoint,
|
||||||
expected,
|
|
||||||
},
|
},
|
||||||
runtime_id: runtime_id.into(),
|
runtime_id: runtime_id.into(),
|
||||||
shared_secret,
|
shared_secret,
|
||||||
|
jwks: Arc::default(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -369,8 +588,7 @@ impl HeimdallClient {
|
||||||
http: Client::new(),
|
http: Client::new(),
|
||||||
issuer: "https://heimdall.invalid".into(),
|
issuer: "https://heimdall.invalid".into(),
|
||||||
public_app_url: "https://ghostlight.invalid/".into(),
|
public_app_url: "https://ghostlight.invalid/".into(),
|
||||||
discord_guild_id: "guild-kltst".into(),
|
providers: vec![AuthProvider::Google, AuthProvider::Discord, AuthProvider::Twitch],
|
||||||
discord_role_id: "role-kltst".into(),
|
|
||||||
boundary_locator: HeimdallBoundaryLocator::Fixed(ResolvedHeimdallBoundary {
|
boundary_locator: HeimdallBoundaryLocator::Fixed(ResolvedHeimdallBoundary {
|
||||||
endpoint: "127.0.0.1:9".parse().unwrap(),
|
endpoint: "127.0.0.1:9".parse().unwrap(),
|
||||||
daemon_id: "yggdrasil-heimdall".into(),
|
daemon_id: "yggdrasil-heimdall".into(),
|
||||||
|
|
@ -383,20 +601,33 @@ impl HeimdallClient {
|
||||||
}),
|
}),
|
||||||
runtime_id: "ghostlight-test-runtime".into(),
|
runtime_id: "ghostlight-test-runtime".into(),
|
||||||
shared_secret: "fixture-secret".into(),
|
shared_secret: "fixture-secret".into(),
|
||||||
|
jwks: Arc::default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn begin(&self, idempotency_key: &str) -> anyhow::Result<AuthBeginReceipt> {
|
/// The same client against another issuer, for tests that stand up their own.
|
||||||
let payload = BeginCommand {
|
#[cfg(test)]
|
||||||
provider: "discord",
|
pub(crate) fn with_issuer(mut self, issuer: impl Into<String>) -> Self {
|
||||||
|
self.issuer = issuer.into();
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
fn begin_command(&self, provider: AuthProvider, grant: bool) -> BeginCommand<'_> {
|
||||||
|
BeginCommand {
|
||||||
|
provider: provider.as_str(),
|
||||||
mode: "sign_in",
|
mode: "sign_in",
|
||||||
return_to: &self.public_app_url,
|
return_to: &self.public_app_url,
|
||||||
entitlement_policy: DiscordRolePolicy {
|
first_login_grant: grant.then_some("invite"),
|
||||||
kind: "discord_role_access",
|
}
|
||||||
guild_id: &self.discord_guild_id,
|
}
|
||||||
allowed_role_ids: [&self.discord_role_id],
|
|
||||||
},
|
pub async fn begin(
|
||||||
};
|
&self,
|
||||||
|
provider: AuthProvider,
|
||||||
|
grant: bool,
|
||||||
|
idempotency_key: &str,
|
||||||
|
) -> anyhow::Result<AuthBeginReceipt> {
|
||||||
|
let payload = self.begin_command(provider, grant);
|
||||||
self.invoke(
|
self.invoke(
|
||||||
"heimdall.auth.begin",
|
"heimdall.auth.begin",
|
||||||
"heimdall.auth_begin_command.v1",
|
"heimdall.auth_begin_command.v1",
|
||||||
|
|
@ -430,11 +661,6 @@ impl HeimdallClient {
|
||||||
let payload = RefreshCommand {
|
let payload = RefreshCommand {
|
||||||
schema: "heimdall.auth_refresh_command.v1",
|
schema: "heimdall.auth_refresh_command.v1",
|
||||||
refresh_token,
|
refresh_token,
|
||||||
entitlement_policy: DiscordRolePolicy {
|
|
||||||
kind: "discord_role_access",
|
|
||||||
guild_id: &self.discord_guild_id,
|
|
||||||
allowed_role_ids: [&self.discord_role_id],
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
self.invoke(
|
self.invoke(
|
||||||
"heimdall.auth.refresh",
|
"heimdall.auth.refresh",
|
||||||
|
|
@ -501,28 +727,43 @@ impl HeimdallClient {
|
||||||
)?))
|
)?))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn fetch_jwks(&self) -> Result<JwkSet, reqwest::Error> {
|
||||||
|
self.http
|
||||||
|
.get(format!("{}/.well-known/jwks.json", self.issuer))
|
||||||
|
.send()
|
||||||
|
.await?
|
||||||
|
.error_for_status()?
|
||||||
|
.json()
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
async fn verify_access(&self, token: &str) -> anyhow::Result<AccessClaims> {
|
async fn verify_access(&self, token: &str) -> anyhow::Result<AccessClaims> {
|
||||||
let header = decode_header(token)?;
|
let header = decode_header(token)?;
|
||||||
if header.alg != Algorithm::EdDSA {
|
if header.alg != Algorithm::EdDSA {
|
||||||
bail!("Heimdall used an unsupported signing algorithm");
|
bail!("Heimdall used an unsupported signing algorithm");
|
||||||
}
|
}
|
||||||
let kid = header.kid.context("Heimdall token omitted kid")?;
|
let kid = header.kid.context("Heimdall token omitted kid")?;
|
||||||
let jwks: JwkSet = self
|
let cached = self.jwks.lock().expect("jwks cache").key(&kid, Instant::now());
|
||||||
.http
|
let jwk = match cached {
|
||||||
.get(format!("{}/.well-known/jwks.json", self.issuer))
|
Some(jwk) => jwk,
|
||||||
.send()
|
None => {
|
||||||
.await?
|
let set = self
|
||||||
.error_for_status()?
|
.fetch_jwks()
|
||||||
.json()
|
.await
|
||||||
.await?;
|
.map_err(|error| VerificationUnavailable::of_fetch(&error))?;
|
||||||
let jwk = jwks
|
let jwk = set.find(&kid).cloned();
|
||||||
.find(&kid)
|
self.jwks
|
||||||
.context("Heimdall signing key was not published")?;
|
.lock()
|
||||||
|
.expect("jwks cache")
|
||||||
|
.store(set, Instant::now());
|
||||||
|
jwk.context("Heimdall signing key was not published")?
|
||||||
|
}
|
||||||
|
};
|
||||||
let mut validation = Validation::new(Algorithm::EdDSA);
|
let mut validation = Validation::new(Algorithm::EdDSA);
|
||||||
validation.set_audience(&[APP_SLUG]);
|
validation.set_audience(&[APP_SLUG]);
|
||||||
validation.set_issuer(&[self.issuer.as_str()]);
|
validation.set_issuer(&[self.issuer.as_str()]);
|
||||||
let claims =
|
let claims =
|
||||||
decode::<AccessClaims>(token, &DecodingKey::from_jwk(jwk)?, &validation)?.claims;
|
decode::<AccessClaims>(token, &DecodingKey::from_jwk(&jwk)?, &validation)?.claims;
|
||||||
if claims.typ != "heimdall_access"
|
if claims.typ != "heimdall_access"
|
||||||
|| claims.aud != APP_SLUG
|
|| claims.aud != APP_SLUG
|
||||||
|| claims.iss != self.issuer
|
|| claims.iss != self.issuer
|
||||||
|
|
@ -580,12 +821,7 @@ impl HeimdallClient {
|
||||||
else {
|
else {
|
||||||
bail!("Heimdall returned a non-operation response");
|
bail!("Heimdall returned a non-operation response");
|
||||||
};
|
};
|
||||||
if status == "denied" {
|
refuse_denied(&status, &diagnostics)?;
|
||||||
bail!(
|
|
||||||
"Heimdall denied the private command: {}",
|
|
||||||
diagnostics.join("; ")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if payload_schema != PRIVATE_ENVELOPE_SCHEMA || payload_encoding != "messagepack-base64" {
|
if payload_schema != PRIVATE_ENVELOPE_SCHEMA || payload_encoding != "messagepack-base64" {
|
||||||
bail!("Heimdall returned the wrong private response contract");
|
bail!("Heimdall returned the wrong private response contract");
|
||||||
}
|
}
|
||||||
|
|
@ -595,6 +831,18 @@ impl HeimdallClient {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A response with status denied is Heimdall's answer, not a transport
|
||||||
|
/// failure: it becomes the typed `HeimdallDenied`.
|
||||||
|
fn refuse_denied(status: &str, diagnostics: &[String]) -> anyhow::Result<()> {
|
||||||
|
if status == "denied" {
|
||||||
|
return Err(HeimdallDenied {
|
||||||
|
diagnostics: diagnostics.join("; "),
|
||||||
|
}
|
||||||
|
.into());
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
fn validate_private_response_binding(
|
fn validate_private_response_binding(
|
||||||
envelope: &PrivateEnvelope,
|
envelope: &PrivateEnvelope,
|
||||||
operation: &str,
|
operation: &str,
|
||||||
|
|
@ -755,13 +1003,7 @@ impl HeimdallBoundaryLocator {
|
||||||
operation: &str,
|
operation: &str,
|
||||||
) -> anyhow::Result<ResolvedHeimdallBoundary> {
|
) -> anyhow::Result<ResolvedHeimdallBoundary> {
|
||||||
let boundary = match self {
|
let boundary = match self {
|
||||||
Self::Odin { endpoint, expected } => {
|
Self::Odin { endpoint } => discover_heimdall_boundary(*endpoint, runtime_id)?,
|
||||||
let boundary = discover_heimdall_boundary(*endpoint, runtime_id)?;
|
|
||||||
if let Some(expected) = expected {
|
|
||||||
require_expected_heimdall_boundary(&boundary, expected)?;
|
|
||||||
}
|
|
||||||
boundary
|
|
||||||
}
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
Self::Fixed(boundary) => boundary.clone(),
|
Self::Fixed(boundary) => boundary.clone(),
|
||||||
};
|
};
|
||||||
|
|
@ -776,16 +1018,6 @@ impl HeimdallBoundaryLocator {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn require_expected_heimdall_boundary(
|
|
||||||
boundary: &ResolvedHeimdallBoundary,
|
|
||||||
expected: &HeimdallDependencyBinding,
|
|
||||||
) -> anyhow::Result<()> {
|
|
||||||
if boundary.daemon_id != expected.provider_id || boundary.endpoint != expected.endpoint {
|
|
||||||
bail!("discovered Heimdall boundary differs from Expected");
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn discover_heimdall_boundary(
|
fn discover_heimdall_boundary(
|
||||||
odin_endpoint: SocketAddr,
|
odin_endpoint: SocketAddr,
|
||||||
runtime_id: &str,
|
runtime_id: &str,
|
||||||
|
|
@ -1006,19 +1238,190 @@ impl PrivateEnvelope {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn required_env(name: &str) -> anyhow::Result<String> {
|
/// A local stand-in for Heimdall's issuer: it serves the key set (or a 5xx)
|
||||||
let value = std::env::var(name).with_context(|| format!("{name} is required"))?;
|
/// on a loopback port and counts the requests it receives. The key is the
|
||||||
let value = value.trim();
|
/// RFC 8037 appendix A.1 Ed25519 test key.
|
||||||
if value.is_empty() {
|
#[cfg(test)]
|
||||||
bail!("{name} must not be empty");
|
pub(crate) mod test_issuer {
|
||||||
|
use super::*;
|
||||||
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||||
|
use tokio::{
|
||||||
|
io::{AsyncReadExt, AsyncWriteExt},
|
||||||
|
net::TcpListener,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub(crate) const KID: &str = "k1";
|
||||||
|
const PRIVATE_D: &str = "nWGxne_9WmC6hEr0kuwsxERJxWl7MmkZcDusAxyuf2A";
|
||||||
|
const PUBLIC_X: &str = "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo";
|
||||||
|
|
||||||
|
#[derive(Clone, Copy)]
|
||||||
|
pub(crate) enum Answer {
|
||||||
|
KeySet,
|
||||||
|
ServerError,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct Issuer {
|
||||||
|
pub(crate) url: String,
|
||||||
|
fetches: Arc<AtomicUsize>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Issuer {
|
||||||
|
pub(crate) async fn start(answer: Answer) -> Self {
|
||||||
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let url = format!("http://{}", listener.local_addr().unwrap());
|
||||||
|
let fetches = Arc::new(AtomicUsize::new(0));
|
||||||
|
let counted = fetches.clone();
|
||||||
|
let key_set = serde_json::json!({
|
||||||
|
"keys": [{"kty": "OKP", "crv": "Ed25519", "kid": KID, "x": PUBLIC_X}]
|
||||||
|
})
|
||||||
|
.to_string();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
while let Ok((mut stream, _)) = listener.accept().await {
|
||||||
|
let mut request = Vec::new();
|
||||||
|
let mut chunk = [0_u8; 1024];
|
||||||
|
while !request.windows(4).any(|window| window == b"\r\n\r\n") {
|
||||||
|
match stream.read(&mut chunk).await {
|
||||||
|
Ok(0) | Err(_) => break,
|
||||||
|
Ok(read) => request.extend_from_slice(&chunk[..read]),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
counted.fetch_add(1, Ordering::SeqCst);
|
||||||
|
let (status, body) = match answer {
|
||||||
|
Answer::KeySet => ("200 OK", key_set.as_str()),
|
||||||
|
Answer::ServerError => ("503 Service Unavailable", ""),
|
||||||
|
};
|
||||||
|
let response = format!(
|
||||||
|
"HTTP/1.1 {status}\r\ncontent-type: application/json\r\n\
|
||||||
|
content-length: {}\r\nconnection: close\r\n\r\n{body}",
|
||||||
|
body.len()
|
||||||
|
);
|
||||||
|
let _ = stream.write_all(response.as_bytes()).await;
|
||||||
|
let _ = stream.shutdown().await;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Self { url, fetches }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn fetches(&self) -> usize {
|
||||||
|
self.fetches.load(Ordering::SeqCst)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The URL of a loopback port nothing listens on.
|
||||||
|
pub(crate) fn closed_url() -> String {
|
||||||
|
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||||
|
format!("http://{}", listener.local_addr().unwrap())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An access token Heimdall's key signs for `issuer`, with the claims
|
||||||
|
/// `verify_access` demands.
|
||||||
|
pub(crate) fn signed_token(issuer: &str) -> String {
|
||||||
|
let mut der = vec![
|
||||||
|
0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22,
|
||||||
|
0x04, 0x20,
|
||||||
|
];
|
||||||
|
der.extend(URL_SAFE_NO_PAD.decode(PRIVATE_D).unwrap());
|
||||||
|
let pem = format!(
|
||||||
|
"-----BEGIN PRIVATE KEY-----\n{}\n-----END PRIVATE KEY-----\n",
|
||||||
|
STANDARD.encode(der)
|
||||||
|
);
|
||||||
|
let mut header = jsonwebtoken::Header::new(Algorithm::EdDSA);
|
||||||
|
header.kid = Some(KID.into());
|
||||||
|
let claims = serde_json::json!({
|
||||||
|
"iss": issuer, "aud": APP_SLUG, "sub": "account-1", "sid": "session-1",
|
||||||
|
"exp": Utc::now().timestamp() + 300, "typ": "heimdall_access",
|
||||||
|
"account_id": "account-1", "access_revision": 1,
|
||||||
|
"capabilities": ["app_access"], "app": {"slug": APP_SLUG},
|
||||||
|
});
|
||||||
|
jsonwebtoken::encode(
|
||||||
|
&header,
|
||||||
|
&claims,
|
||||||
|
&jsonwebtoken::EncodingKey::from_ed_pem(pem.as_bytes()).unwrap(),
|
||||||
|
)
|
||||||
|
.unwrap()
|
||||||
}
|
}
|
||||||
Ok(value.to_owned())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
use super::test_issuer::{Answer, Issuer, signed_token};
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_key_fetch_failure_is_typed_unavailable_and_names_no_url() {
|
||||||
|
let closed = Issuer::closed_url();
|
||||||
|
let failing = Issuer::start(Answer::ServerError).await;
|
||||||
|
for (base, class) in [
|
||||||
|
(closed, "could not connect"),
|
||||||
|
(failing.url.clone(), "returned an error status"),
|
||||||
|
] {
|
||||||
|
let canary = format!("{base}/canary-q7x1");
|
||||||
|
let client = HeimdallClient::fixture().with_issuer(canary.clone());
|
||||||
|
let error = client
|
||||||
|
.verify_access(&signed_token(&canary))
|
||||||
|
.await
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(error.downcast_ref::<VerificationUnavailable>().is_some(), "{error:#}");
|
||||||
|
for text in [format!("{error}"), format!("{error:#}"), format!("{error:?}")] {
|
||||||
|
assert!(text.contains("signing keys unavailable"), "{text}");
|
||||||
|
assert!(text.contains(class), "{text}");
|
||||||
|
for leaked in [canary.as_str(), base.as_str(), "canary-q7x1", "127.0.0.1"] {
|
||||||
|
assert!(!text.contains(leaked), "{leaked} leaked into {text}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn the_key_set_is_fetched_once_within_its_ttl_and_again_after_it() {
|
||||||
|
let issuer = Issuer::start(Answer::KeySet).await;
|
||||||
|
let client = HeimdallClient::fixture().with_issuer(issuer.url.clone());
|
||||||
|
let token = signed_token(&issuer.url);
|
||||||
|
client.verify_access(&token).await.unwrap();
|
||||||
|
assert_eq!(issuer.fetches(), 1);
|
||||||
|
client.verify_access(&token).await.unwrap();
|
||||||
|
assert_eq!(issuer.fetches(), 1, "a second verify within the ttl reads the cache");
|
||||||
|
let age = |seconds: u64| {
|
||||||
|
client.jwks.lock().unwrap().fetched.as_mut().unwrap().0 =
|
||||||
|
Instant::now().checked_sub(Duration::from_secs(seconds)).unwrap();
|
||||||
|
};
|
||||||
|
age(299);
|
||||||
|
client.verify_access(&token).await.unwrap();
|
||||||
|
assert_eq!(issuer.fetches(), 1, "299 s old is still fresh");
|
||||||
|
age(301);
|
||||||
|
client.verify_access(&token).await.unwrap();
|
||||||
|
assert_eq!(issuer.fetches(), 2, "301 s old is fetched again");
|
||||||
|
client.verify_access(&token).await.unwrap();
|
||||||
|
assert_eq!(issuer.fetches(), 2, "and the new fetch is cached");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_token_signed_under_any_other_algorithm_is_refused_before_any_key_fetch() {
|
||||||
|
let issuer = Issuer::start(Answer::KeySet).await;
|
||||||
|
let client = HeimdallClient::fixture().with_issuer(issuer.url.clone());
|
||||||
|
let part = |text: &str| URL_SAFE_NO_PAD.encode(text);
|
||||||
|
for alg in [
|
||||||
|
"none", "HS256", "HS384", "HS512", "RS256", "RS384", "PS256", "ES256", "ES384",
|
||||||
|
] {
|
||||||
|
let token = format!(
|
||||||
|
"{}.{}.{}",
|
||||||
|
part(&format!(r#"{{"alg":"{alg}","typ":"JWT","kid":"k1"}}"#)),
|
||||||
|
part(r#"{"sub":"account-1"}"#),
|
||||||
|
URL_SAFE_NO_PAD.encode([0xAB_u8; 32]),
|
||||||
|
);
|
||||||
|
let error = client.verify_access(&token).await.unwrap_err();
|
||||||
|
assert!(error.downcast_ref::<VerificationUnavailable>().is_none(), "{alg}");
|
||||||
|
if alg != "none" {
|
||||||
|
assert!(
|
||||||
|
error.to_string().contains("unsupported signing algorithm"),
|
||||||
|
"{alg}: {error:#}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert_eq!(issuer.fetches(), 0, "{alg} reached the key fetch");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn boundary(endpoint: &str) -> HeimdallCommandBoundaryRecord {
|
fn boundary(endpoint: &str) -> HeimdallCommandBoundaryRecord {
|
||||||
HeimdallCommandBoundaryRecord {
|
HeimdallCommandBoundaryRecord {
|
||||||
schema: "heimdall.command_boundary.v1".into(),
|
schema: "heimdall.command_boundary.v1".into(),
|
||||||
|
|
@ -1040,6 +1443,34 @@ mod tests {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn key_set(kid: &str) -> JwkSet {
|
||||||
|
serde_json::from_value(serde_json::json!({
|
||||||
|
"keys": [{"kty": "OKP", "crv": "Ed25519", "kid": kid,
|
||||||
|
"x": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"}]
|
||||||
|
}))
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_cached_key_set_serves_until_its_ttl_and_misses_an_unpublished_kid() {
|
||||||
|
let start = Instant::now();
|
||||||
|
let mut cache = JwksCache::default();
|
||||||
|
assert!(cache.key("k1", start).is_none(), "an empty cache has no key");
|
||||||
|
cache.store(key_set("k1"), start);
|
||||||
|
assert!(cache.key("k1", start + Duration::from_secs(299)).is_some());
|
||||||
|
assert!(cache.key("k2", start).is_none(), "a rotated-in kid refetches");
|
||||||
|
assert!(cache.key("k1", start + JWKS_TTL).is_none(), "stale at the ttl");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_denied_status_is_the_typed_denial_and_any_other_status_passes() {
|
||||||
|
let diagnostics = vec!["Idempotency key was reused".to_owned()];
|
||||||
|
let denial = refuse_denied("denied", &diagnostics).unwrap_err();
|
||||||
|
assert!(denial.downcast_ref::<HeimdallDenied>().is_some());
|
||||||
|
assert!(denial.to_string().contains("Idempotency key was reused"));
|
||||||
|
refuse_denied("accepted", &diagnostics).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn private_responses_are_bound_to_the_exact_app_and_request() {
|
fn private_responses_are_bound_to_the_exact_app_and_request() {
|
||||||
let secret = "fixture-shared-secret";
|
let secret = "fixture-shared-secret";
|
||||||
|
|
@ -1143,17 +1574,6 @@ mod tests {
|
||||||
assert_eq!(resolved.endpoint, "127.0.0.1:4101".parse().unwrap());
|
assert_eq!(resolved.endpoint, "127.0.0.1:4101".parse().unwrap());
|
||||||
assert_eq!(resolved.daemon_id, "yggdrasil-heimdall");
|
assert_eq!(resolved.daemon_id, "yggdrasil-heimdall");
|
||||||
assert_eq!(resolved.operations, vec!["heimdall.auth.begin"]);
|
assert_eq!(resolved.operations, vec!["heimdall.auth.begin"]);
|
||||||
let expected = HeimdallDependencyBinding {
|
|
||||||
provider_id: "yggdrasil-heimdall".into(),
|
|
||||||
endpoint: "127.0.0.1:4101".parse().unwrap(),
|
|
||||||
};
|
|
||||||
require_expected_heimdall_boundary(&resolved, &expected)
|
|
||||||
.expect("exact Expected Heimdall should match discovery");
|
|
||||||
let substitute = HeimdallDependencyBinding {
|
|
||||||
provider_id: "another-heimdall".into(),
|
|
||||||
endpoint: expected.endpoint,
|
|
||||||
};
|
|
||||||
assert!(require_expected_heimdall_boundary(&resolved, &substitute).is_err());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
@ -1309,3 +1729,67 @@ mod tests {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod provider_tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn no_begin_or_refresh_carries_a_role_policy_and_the_grant_rides_only_when_asked() {
|
||||||
|
let client = HeimdallClient::fixture();
|
||||||
|
for (provider, name) in [
|
||||||
|
(AuthProvider::Google, "google"),
|
||||||
|
(AuthProvider::Discord, "discord"),
|
||||||
|
(AuthProvider::Twitch, "twitch"),
|
||||||
|
] {
|
||||||
|
let plain = serde_json::to_value(client.begin_command(provider, false)).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
plain,
|
||||||
|
serde_json::json!({"provider": name, "mode": "sign_in", "returnTo": "https://ghostlight.invalid/"}),
|
||||||
|
"no policy, no grant key"
|
||||||
|
);
|
||||||
|
let granted = serde_json::to_value(client.begin_command(provider, true)).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
granted,
|
||||||
|
serde_json::json!({
|
||||||
|
"provider": name,
|
||||||
|
"mode": "sign_in",
|
||||||
|
"returnTo": "https://ghostlight.invalid/",
|
||||||
|
"firstLoginGrant": "invite",
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let refresh = serde_json::to_value(RefreshCommand {
|
||||||
|
schema: "heimdall.auth_refresh_command.v1",
|
||||||
|
refresh_token: "r",
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(refresh, serde_json::json!({"schema": "heimdall.auth_refresh_command.v1", "refreshToken": "r"}));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_offered_set_is_the_configured_set() {
|
||||||
|
let mut client = HeimdallClient::fixture();
|
||||||
|
client.providers = vec![AuthProvider::Discord, AuthProvider::Google];
|
||||||
|
assert_eq!(client.offered("google"), Some(AuthProvider::Google));
|
||||||
|
assert_eq!(client.offered("discord"), Some(AuthProvider::Discord));
|
||||||
|
assert_eq!(client.offered("twitch"), None);
|
||||||
|
assert_eq!(client.offered("Google"), None);
|
||||||
|
assert_eq!(client.offered("patreon"), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_provider_list_names_only_known_providers_and_at_least_one() {
|
||||||
|
assert_eq!(
|
||||||
|
AuthProvider::set_from("google, discord,google").unwrap(),
|
||||||
|
vec![AuthProvider::Google, AuthProvider::Discord]
|
||||||
|
);
|
||||||
|
assert_eq!(AuthProvider::set_from("twitch").unwrap(), vec![AuthProvider::Twitch]);
|
||||||
|
for bad in ["", " , ", "github", "discord,patreon"] {
|
||||||
|
assert!(AuthProvider::set_from(bad).is_err(), "{bad:?}");
|
||||||
|
}
|
||||||
|
for provider in [AuthProvider::Google, AuthProvider::Discord, AuthProvider::Twitch] {
|
||||||
|
assert_eq!(AuthProvider::parse(provider.as_str()), Some(provider));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -44,24 +44,9 @@ pub const IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT: &str = "GAMECULT_IDUNN_CANDI
|
||||||
pub const IDUNN_PROCESS_WRITE_LEASE_ENVIRONMENT: &str = "GAMECULT_IDUNN_PROCESS_WRITE_LEASE";
|
pub const IDUNN_PROCESS_WRITE_LEASE_ENVIRONMENT: &str = "GAMECULT_IDUNN_PROCESS_WRITE_LEASE";
|
||||||
|
|
||||||
pub(crate) const TARGET: &str = "ghostlight";
|
pub(crate) const TARGET: &str = "ghostlight";
|
||||||
const STATE_SCHEMA_GENERATION: &str = "world-v3";
|
const STATE_SCHEMA_GENERATION: &str = "dungeon-v1";
|
||||||
const STATE_CONTRACT_SHA256: &str =
|
const STATE_CONTRACT_SHA256: &str =
|
||||||
"sha256-4ac3d4ceabedc48b4fc5a3c143ece00ac495d8d756bdc24f10034bcc1231970f";
|
"sha256-f7a7e4206608cb4c47a867b02146f8657201ab10eab3937d1bb8c37fe6d605ef";
|
||||||
/// The exact `[state]` + `[[state.slots]]` text in `deployment/idunn/recipe.toml`
|
|
||||||
/// that `STATE_CONTRACT_SHA256` above was computed from (Idunn's own
|
|
||||||
/// `canonical_state_contract_sha256`: msgpack-encode the recipe's own parsed
|
|
||||||
/// `[state]` struct, then sha256 it — run against the finalized recipe, not
|
|
||||||
/// hand-derived). These two constants change together: whoever edits the
|
|
||||||
/// recipe's `[state]` block must recompute `STATE_CONTRACT_SHA256` the same
|
|
||||||
/// way and update both, or `recipe_matches_the_daemon_it_deploys` (below)
|
|
||||||
/// fails on the text pin without saying the hash is wrong — which is the
|
|
||||||
/// point: the test cannot recompute the hash itself (no TOML parser or
|
|
||||||
/// msgpack encoder in this crate's dependency graph), so pinning the source
|
|
||||||
/// text is the cheapest honest proxy for "the hash still matches this text".
|
|
||||||
/// LF line endings: the committed git blob is LF-only; this constant matches
|
|
||||||
/// that, not whatever CRLF a Windows checkout's autocrlf produces locally.
|
|
||||||
#[cfg(test)]
|
|
||||||
const EXPECTED_STATE_AND_SLOTS_TEXT: &str = "[state]\nschema_generation = \"world-v3\"\n\n[[state.slots]]\nid = \"world\"\nrelative_path = \"world.cc\"\nkind = \"cultcache-file\"\nschema = \"ghostlight.world_state.consumer.v6\"\nwriter = \"process-bound-single-writer\"\nrecovery = \"preserve\"\nstartup = \"create-or-open-after-write-lease\"\n\n[[state.slots]]\nid = \"app-sessions\"\nrelative_path = \"service/app-sessions-v2.cc\"\nkind = \"cultcache-file\"\nschema = \"ghostlight.app_session_store.v2\"\nwriter = \"process-bound-single-writer\"\nrecovery = \"preserve\"\nstartup = \"create-or-open-after-write-lease\"\n\n[[state.slots]]\nid = \"controller-work\"\nrelative_path = \"service/controller-work.cc\"\nkind = \"cultcache-file\"\nschema = \"ghostlight.controller_work.v17\"\nwriter = \"process-bound-single-writer\"\nrecovery = \"preserve\"\nstartup = \"create-or-open-after-write-lease\"\n\n[[state.slots]]\nid = \"mesh-projection\"\nrelative_path = \"service/mesh-v2.cc\"\nkind = \"cultcache-file\"\nschema = \"gamecult.eve.surface.v1\"\nwriter = \"process-bound-single-writer\"\nrecovery = \"rebuildable\"\nstartup = \"create-or-open-after-write-lease\"\n\n";
|
|
||||||
const CULTNET_RUDP_PROTOCOL_ID: &str = "cultnet.transport.rudp.v0";
|
const CULTNET_RUDP_PROTOCOL_ID: &str = "cultnet.transport.rudp.v0";
|
||||||
const ODIN_CULTMESH_CATALOG_CONNECTION_ID: u32 = 0x0d1d_0002;
|
const ODIN_CULTMESH_CATALOG_CONNECTION_ID: u32 = 0x0d1d_0002;
|
||||||
const RUNTIME_PRESENCE_IDENTITY_FD_NAME: &str = "gamecult-runtime-presence-identity";
|
const RUNTIME_PRESENCE_IDENTITY_FD_NAME: &str = "gamecult-runtime-presence-identity";
|
||||||
|
|
@ -176,7 +161,7 @@ impl RuntimePresencePublisher {
|
||||||
expected.state_schema_generation.as_deref() == Some(STATE_SCHEMA_GENERATION)
|
expected.state_schema_generation.as_deref() == Some(STATE_SCHEMA_GENERATION)
|
||||||
&& expected.state_contract_sha256.as_deref() == Some(STATE_CONTRACT_SHA256)
|
&& expected.state_contract_sha256.as_deref() == Some(STATE_CONTRACT_SHA256)
|
||||||
&& expected.write_lease_required,
|
&& expected.write_lease_required,
|
||||||
"Expected does not name Ghostlight's writable world-v3 state"
|
"Expected does not name the Dungeon's writable dungeon-v1 state"
|
||||||
);
|
);
|
||||||
ensure!(
|
ensure!(
|
||||||
activation.expected_projection_sha256 == expected.canonical_sha256()?
|
activation.expected_projection_sha256 == expected.canonical_sha256()?
|
||||||
|
|
@ -975,12 +960,6 @@ impl Drop for ProcessWriteLeaseGuard {
|
||||||
|
|
||||||
fn actual_capabilities() -> Vec<GameCultRuntimeCapability> {
|
fn actual_capabilities() -> Vec<GameCultRuntimeCapability> {
|
||||||
vec![
|
vec![
|
||||||
GameCultRuntimeCapability {
|
|
||||||
capability: "gamecult.eve.surface-provider".into(),
|
|
||||||
schema: "gamecult.eve.surface.v1".into(),
|
|
||||||
compatibility: "v1".into(),
|
|
||||||
capacity: 1,
|
|
||||||
},
|
|
||||||
GameCultRuntimeCapability {
|
GameCultRuntimeCapability {
|
||||||
capability: "ghostlight.world-service".into(),
|
capability: "ghostlight.world-service".into(),
|
||||||
schema: STATE_SCHEMA.into(),
|
schema: STATE_SCHEMA.into(),
|
||||||
|
|
@ -1271,12 +1250,6 @@ pub(crate) mod tests {
|
||||||
candidate_endpoint: "http://127.0.0.1:18831".into(),
|
candidate_endpoint: "http://127.0.0.1:18831".into(),
|
||||||
}),
|
}),
|
||||||
capabilities: vec![
|
capabilities: vec![
|
||||||
IdunnExpectedCapability {
|
|
||||||
capability: "gamecult.eve.surface-provider".into(),
|
|
||||||
schema: "gamecult.eve.surface.v1".into(),
|
|
||||||
compatibility: "v1".into(),
|
|
||||||
minimum_capacity: 1,
|
|
||||||
},
|
|
||||||
IdunnExpectedCapability {
|
IdunnExpectedCapability {
|
||||||
capability: "ghostlight.world-service".into(),
|
capability: "ghostlight.world-service".into(),
|
||||||
schema: STATE_SCHEMA.into(),
|
schema: STATE_SCHEMA.into(),
|
||||||
|
|
@ -1438,7 +1411,7 @@ pub(crate) mod tests {
|
||||||
assert!(
|
assert!(
|
||||||
error
|
error
|
||||||
.to_string()
|
.to_string()
|
||||||
.contains("does not name Ghostlight's writable world-v3 state")
|
.contains("does not name the Dungeon's writable dungeon-v1 state")
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1634,149 +1607,6 @@ pub(crate) mod tests {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// No TOML parser is in this workspace's dependency graph (checked
|
|
||||||
/// `Cargo.lock`), so this pins the exact strings the daemon's own
|
|
||||||
/// constants require rather than parsing the recipe into a struct. It
|
|
||||||
/// still catches the drift class Soul found: the recipe naming a state
|
|
||||||
/// generation, provided schema, slot schema, or dependency shape the
|
|
||||||
/// binary does not actually have (F2). Every field is anchored to its own
|
|
||||||
/// table block (Soul's second pass: a bare `.contains()` anywhere in the
|
|
||||||
/// file passed even when the matched value sat under the wrong table —
|
|
||||||
/// e.g. a schema correct in `[[provides]]` but wrong in its own state
|
|
||||||
/// slot).
|
|
||||||
const RECIPE_TOML: &str = include_str!(concat!(
|
|
||||||
env!("CARGO_MANIFEST_DIR"),
|
|
||||||
"/../../deployment/idunn/recipe.toml"
|
|
||||||
));
|
|
||||||
|
|
||||||
/// Splits recipe text into blocks, each running from one line whose first
|
|
||||||
/// non-whitespace byte is `[` up to (not including) the next such line.
|
|
||||||
/// Assertions then search *within* the right block instead of the whole
|
|
||||||
/// file, so a value in the wrong table cannot satisfy them.
|
|
||||||
fn recipe_blocks(text: &str) -> Vec<&str> {
|
|
||||||
let mut starts = Vec::new();
|
|
||||||
let mut offset = 0usize;
|
|
||||||
for line in text.split_inclusive('\n') {
|
|
||||||
if line.trim_start().starts_with('[') {
|
|
||||||
starts.push(offset);
|
|
||||||
}
|
|
||||||
offset += line.len();
|
|
||||||
}
|
|
||||||
starts.push(text.len());
|
|
||||||
starts.windows(2).map(|pair| &text[pair[0]..pair[1]]).collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The one block whose header matches `header` and whose body contains
|
|
||||||
/// `anchor` (e.g. `id = "world"`, or `capability = "..."`) — the field
|
|
||||||
/// that names which real table this is, distinct from every other block
|
|
||||||
/// sharing the same header (there are four `[[state.slots]]` blocks, two
|
|
||||||
/// `[[provides]]` blocks, two `[[dependencies]]` blocks).
|
|
||||||
fn find_block<'a>(blocks: &[&'a str], header: &str, anchor: &str) -> &'a str {
|
|
||||||
blocks
|
|
||||||
.iter()
|
|
||||||
.copied()
|
|
||||||
.find(|block| block.trim_start().starts_with(header) && block.contains(anchor))
|
|
||||||
.unwrap_or_else(|| panic!("recipe has no {header} block containing {anchor:?}"))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn recipe_matches_the_daemon_it_deploys() {
|
|
||||||
let blocks = recipe_blocks(RECIPE_TOML);
|
|
||||||
|
|
||||||
let world_service = find_block(
|
|
||||||
&blocks,
|
|
||||||
"[[provides]]",
|
|
||||||
"capability = \"ghostlight.world-service\"",
|
|
||||||
);
|
|
||||||
assert!(
|
|
||||||
world_service.contains(&format!("schema = \"{STATE_SCHEMA}\"")),
|
|
||||||
"recipe [[provides]] ghostlight.world-service schema disagrees with STATE_SCHEMA"
|
|
||||||
);
|
|
||||||
assert!(
|
|
||||||
world_service.contains(&format!(
|
|
||||||
"compatibility = \"{}\"",
|
|
||||||
state_schema_compatibility_tag()
|
|
||||||
)),
|
|
||||||
"recipe [[provides]] ghostlight.world-service compatibility disagrees with state_schema_compatibility_tag()"
|
|
||||||
);
|
|
||||||
|
|
||||||
let world_slot = find_block(&blocks, "[[state.slots]]", "id = \"world\"");
|
|
||||||
assert!(
|
|
||||||
world_slot.contains(&format!("schema = \"{STATE_SCHEMA}\"")),
|
|
||||||
"recipe world state slot schema disagrees with STATE_SCHEMA"
|
|
||||||
);
|
|
||||||
|
|
||||||
let app_sessions_slot = find_block(&blocks, "[[state.slots]]", "id = \"app-sessions\"");
|
|
||||||
assert!(
|
|
||||||
app_sessions_slot.contains(&format!(
|
|
||||||
"schema = \"{}\"",
|
|
||||||
crate::app_session::STORE_SCHEMA
|
|
||||||
)),
|
|
||||||
"recipe app-sessions slot schema disagrees with app_session::STORE_SCHEMA"
|
|
||||||
);
|
|
||||||
|
|
||||||
let controller_work_slot =
|
|
||||||
find_block(&blocks, "[[state.slots]]", "id = \"controller-work\"");
|
|
||||||
assert!(
|
|
||||||
controller_work_slot
|
|
||||||
.contains(&format!("schema = \"{}\"", ghostlight::CONTROLLER_WORK_SCHEMA)),
|
|
||||||
"recipe controller-work slot schema disagrees with ghostlight::CONTROLLER_WORK_SCHEMA"
|
|
||||||
);
|
|
||||||
|
|
||||||
let mesh_slot = find_block(&blocks, "[[state.slots]]", "id = \"mesh-projection\"");
|
|
||||||
assert!(
|
|
||||||
mesh_slot.contains("schema = \"gamecult.eve.surface.v1\""),
|
|
||||||
"recipe mesh-projection slot schema disagrees with the mesh module's eve surface schema"
|
|
||||||
);
|
|
||||||
|
|
||||||
let dependency_blocks: Vec<&&str> = blocks
|
|
||||||
.iter()
|
|
||||||
.filter(|block| block.trim_start().starts_with("[[dependencies]]"))
|
|
||||||
.collect();
|
|
||||||
assert_eq!(
|
|
||||||
dependency_blocks.len(),
|
|
||||||
1,
|
|
||||||
"recipe does not declare Ghostlight's exact one dependency \
|
|
||||||
(Heimdall is discovered through Odin at use, not an Idunn \
|
|
||||||
dependency, until Heimdall is a v2 target — see \
|
|
||||||
runtime_dependency_bindings)"
|
|
||||||
);
|
|
||||||
|
|
||||||
let odin_dependency = find_block(
|
|
||||||
&blocks,
|
|
||||||
"[[dependencies]]",
|
|
||||||
&format!("capability = \"{}\"", ODIN_CAPABILITY.0),
|
|
||||||
);
|
|
||||||
assert!(
|
|
||||||
odin_dependency.contains("kind = \"shared-infrastructure\""),
|
|
||||||
"recipe Odin dependency kind disagrees with idunn_health's managed-shared-infrastructure rule"
|
|
||||||
);
|
|
||||||
|
|
||||||
assert!(
|
|
||||||
!RECIPE_TOML.contains("gamecult.codex.subscription-inference"),
|
|
||||||
"recipe still declares the retired CodexConnector dependency"
|
|
||||||
);
|
|
||||||
|
|
||||||
// STATE_CONTRACT_SHA256 pin (S3): the test cannot recompute Idunn's
|
|
||||||
// hash itself (no TOML parser or msgpack encoder here), so it pins
|
|
||||||
// the exact [state]+[[state.slots]] source text the hash was
|
|
||||||
// computed from instead. A change to that text without recomputing
|
|
||||||
// and updating STATE_CONTRACT_SHA256 to match fails here.
|
|
||||||
let start = RECIPE_TOML
|
|
||||||
.find("[state]")
|
|
||||||
.expect("recipe has a [state] block");
|
|
||||||
let end = RECIPE_TOML
|
|
||||||
.find("[[provides]]")
|
|
||||||
.expect("recipe [state] block is followed by [[provides]]");
|
|
||||||
let state_and_slots_text = RECIPE_TOML[start..end].replace("\r\n", "\n");
|
|
||||||
assert_eq!(
|
|
||||||
state_and_slots_text, EXPECTED_STATE_AND_SLOTS_TEXT,
|
|
||||||
"recipe [state]/[[state.slots]] text changed without updating \
|
|
||||||
STATE_CONTRACT_SHA256 and EXPECTED_STATE_AND_SLOTS_TEXT together \
|
|
||||||
(recompute the hash with Idunn's canonical_state_contract_sha256 \
|
|
||||||
against the new recipe)"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A failed heartbeat publish does not abort `wait_for_write_lease`. The
|
/// A failed heartbeat publish does not abort `wait_for_write_lease`. The
|
||||||
/// fixture publisher's endpoint (`127.0.0.1:9`) is closed, so every
|
/// fixture publisher's endpoint (`127.0.0.1:9`) is closed, so every
|
||||||
|
|
@ -1999,3 +1829,142 @@ pub(crate) mod tests {
|
||||||
assert!(!is_root_read_only_file(0, 4_000, 0o446));
|
assert!(!is_root_read_only_file(0, 4_000, 0o446));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The recipe and the binary agree on the state Idunn fences. The recipe's
|
||||||
|
/// `[state]` block is Idunn's input; `STATE_CONTRACT_SHA256` is the digest the
|
||||||
|
/// daemon admits it by. Both are derived here from one typed table, so a slot
|
||||||
|
/// edited in either place, or a schema constant bumped in code, fails a test
|
||||||
|
/// instead of failing a deploy.
|
||||||
|
#[cfg(test)]
|
||||||
|
mod recipe_drift {
|
||||||
|
use super::*;
|
||||||
|
use serde::Serialize;
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
|
const RECIPE_TOML: &str = include_str!(concat!(
|
||||||
|
env!("CARGO_MANIFEST_DIR"),
|
||||||
|
"/../../deployment/idunn/recipe.toml"
|
||||||
|
));
|
||||||
|
|
||||||
|
// Mirrors Idunn's `StateDeclaration` wire shape: field order and the
|
||||||
|
// kebab-case unit variants decide the bytes it hashes.
|
||||||
|
#[derive(Serialize)]
|
||||||
|
struct Declaration {
|
||||||
|
schema_generation: &'static str,
|
||||||
|
slots: Vec<Slot>,
|
||||||
|
migration: Option<()>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
struct Slot {
|
||||||
|
id: &'static str,
|
||||||
|
relative_path: &'static str,
|
||||||
|
kind: &'static str,
|
||||||
|
schema: &'static str,
|
||||||
|
writer: &'static str,
|
||||||
|
recovery: &'static str,
|
||||||
|
startup: &'static str,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn slot(id: &'static str, path: &'static str, kind: &'static str, schema: &'static str, recovery: &'static str) -> Slot {
|
||||||
|
Slot {
|
||||||
|
id,
|
||||||
|
relative_path: path,
|
||||||
|
kind,
|
||||||
|
schema,
|
||||||
|
writer: "process-bound-single-writer",
|
||||||
|
recovery,
|
||||||
|
startup: "create-or-open-after-write-lease",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The slots the daemon opens, each schema read from the code that owns it.
|
||||||
|
fn declaration() -> Declaration {
|
||||||
|
Declaration {
|
||||||
|
schema_generation: STATE_SCHEMA_GENERATION,
|
||||||
|
slots: vec![
|
||||||
|
slot("catalog", "catalog.cc", "cultcache-file", crate::catalog::STORE_TYPE, "preserve"),
|
||||||
|
slot("app-sessions", "service/app-sessions-v2.cc", "cultcache-file", crate::app_session::STORE_SCHEMA, "preserve"),
|
||||||
|
slot("snapshots", crate::vaults::SNAPSHOT_DIRECTORY, "external-file", ghostlight::VAULT_SNAPSHOT_SCHEMA, "rebuildable"),
|
||||||
|
slot("timelines", "timelines", "external-file", STATE_SCHEMA, "preserve"),
|
||||||
|
],
|
||||||
|
migration: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn state_text(declaration: &Declaration) -> String {
|
||||||
|
let mut text = format!("[state]\nschema_generation = \"{}\"\n\n", declaration.schema_generation);
|
||||||
|
for slot in &declaration.slots {
|
||||||
|
text += &format!(
|
||||||
|
"[[state.slots]]\nid = \"{}\"\nrelative_path = \"{}\"\nkind = \"{}\"\nschema = \"{}\"\nwriter = \"{}\"\nrecovery = \"{}\"\nstartup = \"{}\"\n\n",
|
||||||
|
slot.id, slot.relative_path, slot.kind, slot.schema, slot.writer, slot.recovery, slot.startup
|
||||||
|
);
|
||||||
|
}
|
||||||
|
text
|
||||||
|
}
|
||||||
|
|
||||||
|
fn contract_sha256(declaration: &Declaration) -> String {
|
||||||
|
let bytes = rmp_serde::to_vec(declaration).expect("the declaration encodes");
|
||||||
|
let digest = Sha256::digest(bytes);
|
||||||
|
format!("sha256-{}", digest.iter().map(|byte| format!("{byte:02x}")).collect::<String>())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The recipe's `[state]` through its last slot, line endings folded.
|
||||||
|
fn recipe_state(recipe: &str) -> String {
|
||||||
|
let start = recipe.find("[state]").expect("recipe has a [state] block");
|
||||||
|
let end = recipe.find("[[provides]]").expect("[state] is followed by [[provides]]");
|
||||||
|
recipe[start..end].replace("\r\n", "\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_recipe_state_is_the_contract_the_daemon_admits() {
|
||||||
|
let declaration = declaration();
|
||||||
|
assert_eq!(
|
||||||
|
recipe_state(RECIPE_TOML),
|
||||||
|
state_text(&declaration),
|
||||||
|
"recipe [state] differs from the slots the daemon opens"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
STATE_CONTRACT_SHA256,
|
||||||
|
contract_sha256(&declaration),
|
||||||
|
"STATE_CONTRACT_SHA256 is not the digest of the slots the recipe declares"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_edited_slot_or_schema_is_caught() {
|
||||||
|
let declaration = declaration();
|
||||||
|
for (from, to) in [
|
||||||
|
("catalog.cc", "catalog-v2.cc"),
|
||||||
|
("ghostlight.vault_snapshot.v1", "ghostlight.vault_snapshot.v2"),
|
||||||
|
("recovery = \"rebuildable\"", "recovery = \"preserve\""),
|
||||||
|
("dungeon-v1", "dungeon-v2"),
|
||||||
|
] {
|
||||||
|
let drifted = RECIPE_TOML.replacen(from, to, 1);
|
||||||
|
assert_ne!(drifted, RECIPE_TOML, "{from} is not in the recipe");
|
||||||
|
assert_ne!(recipe_state(&drifted), state_text(&declaration), "{from} -> {to} went unseen");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_recipe_provides_what_the_daemon_provides_and_nothing_retired() {
|
||||||
|
let provided = format!(
|
||||||
|
"capability = \"ghostlight.world-service\"\nschema = \"{STATE_SCHEMA}\"\ncompatibility = \"{}\"",
|
||||||
|
state_schema_compatibility_tag()
|
||||||
|
);
|
||||||
|
assert!(RECIPE_TOML.contains(&provided), "recipe [[provides]] disagrees with actual_capabilities()");
|
||||||
|
assert_eq!(RECIPE_TOML.matches("[[provides]]").count(), 1);
|
||||||
|
let odin = format!(
|
||||||
|
"kind = \"shared-infrastructure\"\ncapability = \"{}\"\nschema = \"{}\"\ncompatibility = \"{}\"",
|
||||||
|
ODIN_CAPABILITY.0, ODIN_CAPABILITY.1, ODIN_CAPABILITY.2
|
||||||
|
);
|
||||||
|
assert!(RECIPE_TOML.contains(&odin), "recipe Odin dependency disagrees with ODIN_CAPABILITY");
|
||||||
|
assert_eq!(RECIPE_TOML.matches("[[dependencies]]").count(), 1);
|
||||||
|
let lowered = RECIPE_TOML.to_lowercase();
|
||||||
|
for word in ["eve", "mesh", "codexconnector", "codex-connector", "web-build", "npm"] {
|
||||||
|
assert!(!lowered.split(|c: char| !c.is_alphanumeric() && c != '-').any(|token| token == word), "recipe names {word}");
|
||||||
|
}
|
||||||
|
assert!(!lowered.contains("connection-ghostlight.key"), "the key path belongs to the operator binding");
|
||||||
|
assert!(!lowered.contains("credentials_directory"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
211
crates/ghostlight-dungeon/src/invite.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:#}");
|
||||||
|
}
|
||||||
|
}
|
||||||
658
crates/ghostlight-dungeon/src/knobs.rs
Normal file
658
crates/ghostlight-dungeon/src/knobs.rs
Normal file
|
|
@ -0,0 +1,658 @@
|
||||||
|
//! The DM's gears: one timeline's standing knobs for the world beyond the room.
|
||||||
|
//!
|
||||||
|
//! The document is scheduling state, never world truth. It holds how often each
|
||||||
|
//! distance band takes a turn, how far the focus opens, how many node turns a
|
||||||
|
//! wave may spend, what each background lane may spend in one post-turn window,
|
||||||
|
//! the focus the DM added with a lease in fictional minutes, and the nodes the
|
||||||
|
//! DM asked to run now. The planner and the elaborator's sweep read it; nothing
|
||||||
|
//! else decides how much the world beyond the room moves. The DM changes it only
|
||||||
|
//! through the `tune` and `run_world` tools, and the player's own place is never
|
||||||
|
//! in it: that focus is derived from the world each time.
|
||||||
|
//!
|
||||||
|
//! Demotion is lazy. A lease names the fictional minute it ends at; past it the
|
||||||
|
//! entry is simply not focus, and the next `tune` drops it from the document.
|
||||||
|
//! Every wave records the knobs it planned under.
|
||||||
|
|
||||||
|
use anyhow::Context;
|
||||||
|
use chrono::Utc;
|
||||||
|
use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore};
|
||||||
|
use ghostlight::{
|
||||||
|
CoverBudget, EntityId, GestaltKnobs, Hierarchy, LaneTokens, NodeAnchor, NodeId, RecordedKnobs, SubjectId,
|
||||||
|
SubjectKind, TickMinutes, WorldSnapshot, id_text, id_text_matches, node_label,
|
||||||
|
};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use serde_json::Value;
|
||||||
|
use std::{ops::RangeInclusive, path::Path, sync::Arc};
|
||||||
|
use tokio::sync::Mutex;
|
||||||
|
|
||||||
|
const TYPE: &str = "ghostlight.dungeon_gestalt_knobs.v1";
|
||||||
|
const KEY: &str = "knobs";
|
||||||
|
|
||||||
|
/// The longest a band period or a lease may be: the clock's own span.
|
||||||
|
const LONGEST_MINUTES: i64 = 525_600;
|
||||||
|
const MOST_BANDS: usize = 8;
|
||||||
|
const DEPTHS: RangeInclusive<i64> = 1..=8;
|
||||||
|
const NODE_TURNS: RangeInclusive<i64> = 1..=32;
|
||||||
|
const MOST_ALLOWANCE: i64 = 5_000_000;
|
||||||
|
/// Leases and forced nodes the document holds at once.
|
||||||
|
const MOST_ENTRIES: usize = 8;
|
||||||
|
|
||||||
|
/// What a focus entry or a forced run names: a place, or an institution whose
|
||||||
|
/// node it is. Both are ids `table_view` prints.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub(crate) enum Target {
|
||||||
|
Place(EntityId),
|
||||||
|
Institution(SubjectId),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Target {
|
||||||
|
/// What the world calls the target, `-` when it no longer holds it.
|
||||||
|
pub(crate) fn label(&self, world: &WorldSnapshot) -> String {
|
||||||
|
target_label(self, world)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn text(&self) -> String {
|
||||||
|
match self {
|
||||||
|
Self::Place(id) => id_text(id),
|
||||||
|
Self::Institution(id) => id_text(id),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The node this target stands for in `hierarchy`: the node that governs a
|
||||||
|
/// place, an institution's own node. None for an institution the hierarchy
|
||||||
|
/// no longer holds.
|
||||||
|
pub(crate) fn node(&self, hierarchy: &Hierarchy) -> Option<NodeId> {
|
||||||
|
match self {
|
||||||
|
Self::Place(place) => hierarchy.focus_path(*place).first().copied(),
|
||||||
|
Self::Institution(subject) => hierarchy
|
||||||
|
.nodes
|
||||||
|
.values()
|
||||||
|
.find(|node| node.anchor == NodeAnchor::Institution(*subject))
|
||||||
|
.map(|node| node.id),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A focus entry the DM added: it holds until the world's clock reaches `until`.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub(crate) struct Lease {
|
||||||
|
pub(crate) target: Target,
|
||||||
|
pub(crate) until: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One timeline's knobs, document `ghostlight.dungeon_gestalt_knobs.v1`.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub(crate) struct DmKnobs {
|
||||||
|
pub(crate) knobs: RecordedKnobs,
|
||||||
|
/// What each background lane may spend in one post-turn window.
|
||||||
|
pub(crate) allowances: LaneTokens,
|
||||||
|
pub(crate) focus: Vec<Lease>,
|
||||||
|
/// Nodes the DM asked to run in the next post-turn wave; that wave takes them.
|
||||||
|
pub(crate) forced: Vec<Target>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for DmKnobs {
|
||||||
|
/// A Begin's knobs: bands of an hour, six hours, a day and a week by
|
||||||
|
/// distance from the focus, the focus opened two nodes up, four node turns
|
||||||
|
/// a wave, each node's cover at four cells of six, and the allowances sized
|
||||||
|
/// to what the retired four-session sweep and its wave were: no cost has
|
||||||
|
/// been measured yet, so the DM tunes from the averages its view prints.
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
knobs: RecordedKnobs {
|
||||||
|
bands: vec![60, 360, 1440, 10_080],
|
||||||
|
depth: 2,
|
||||||
|
max_node_turns: 4,
|
||||||
|
cells: 4,
|
||||||
|
constituent_cap: 6,
|
||||||
|
urgency_slots: 1,
|
||||||
|
},
|
||||||
|
allowances: LaneTokens { wave: 200_000, elaboration: 200_000 },
|
||||||
|
focus: Vec::new(),
|
||||||
|
forced: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DmKnobs {
|
||||||
|
/// The planner's knobs. A document whose values the planner would refuse
|
||||||
|
/// never reaches it: `tune` admits only values this reads.
|
||||||
|
pub(crate) fn gestalt(&self) -> anyhow::Result<GestaltKnobs> {
|
||||||
|
let bands = self
|
||||||
|
.knobs
|
||||||
|
.bands
|
||||||
|
.iter()
|
||||||
|
.map(|minutes| TickMinutes::new(*minutes).with_context(|| format!("band {minutes} is outside the clock's span")))
|
||||||
|
.collect::<anyhow::Result<Vec<_>>>()?;
|
||||||
|
let knobs = GestaltKnobs {
|
||||||
|
bands,
|
||||||
|
depth: self.knobs.depth,
|
||||||
|
max_node_turns: self.knobs.max_node_turns,
|
||||||
|
cover: CoverBudget {
|
||||||
|
cells: self.knobs.cells,
|
||||||
|
constituent_cap: self.knobs.constituent_cap,
|
||||||
|
urgency_slots: self.knobs.urgency_slots,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
knobs.validate()?;
|
||||||
|
Ok(knobs)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The DM's focus entries still holding at fictional minute `now`.
|
||||||
|
pub(crate) fn standing(&self, now: u64) -> impl Iterator<Item = &Lease> {
|
||||||
|
self.focus.iter().filter(move |lease| lease.until > now)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The timeline's knobs in one CultCache file.
|
||||||
|
pub(crate) struct KnobStore {
|
||||||
|
store: OwnedRedbMessagePackBackingStore,
|
||||||
|
knobs: DmKnobs,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) type KnobLog = Arc<Mutex<KnobStore>>;
|
||||||
|
|
||||||
|
impl KnobStore {
|
||||||
|
/// Opens the file, writing a Begin's knobs into a timeline that has none.
|
||||||
|
pub(crate) fn open(path: impl AsRef<Path>) -> anyhow::Result<Self> {
|
||||||
|
let store = OwnedRedbMessagePackBackingStore::new(path.as_ref())?;
|
||||||
|
store.validate_path_identity().context("knob store path identity is invalid")?;
|
||||||
|
let mut rows = store.pull_all()?;
|
||||||
|
let knobs = match rows.pop() {
|
||||||
|
None => None,
|
||||||
|
Some(row) => {
|
||||||
|
anyhow::ensure!(rows.is_empty() && row.r#type == TYPE && row.key == KEY, "the knob store holds a foreign record");
|
||||||
|
Some(rmp_serde::from_slice::<DmKnobs>(&row.payload).context("the knobs did not decode")?)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let mut opened = Self { store, knobs: knobs.clone().unwrap_or_default() };
|
||||||
|
opened.knobs.gestalt().context("the stored knobs are not plannable")?;
|
||||||
|
if knobs.is_none() {
|
||||||
|
opened.replace(opened.knobs.clone())?;
|
||||||
|
}
|
||||||
|
Ok(opened)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn current(&self) -> DmKnobs {
|
||||||
|
self.knobs.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn replace(&mut self, knobs: DmKnobs) -> anyhow::Result<()> {
|
||||||
|
let row = CultCacheEnvelope {
|
||||||
|
key: KEY.into(),
|
||||||
|
r#type: TYPE.into(),
|
||||||
|
payload: rmp_serde::to_vec_named(&knobs)?,
|
||||||
|
stored_at: Utc::now().to_rfc3339(),
|
||||||
|
schema_id: Some(TYPE.into()),
|
||||||
|
};
|
||||||
|
self.store.validate_path_identity().context("knob store ownership was lost")?;
|
||||||
|
self.store.push(&row)?;
|
||||||
|
self.knobs = knobs;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A whole number inside `range`, or the refusal quoting what was given.
|
||||||
|
fn whole(name: &str, value: &Value, range: RangeInclusive<i64>) -> Result<i64, String> {
|
||||||
|
let Some(number) = value.as_i64() else {
|
||||||
|
return Err(format!("{name} must be a whole number, got {value}"));
|
||||||
|
};
|
||||||
|
if range.contains(&number) {
|
||||||
|
Ok(number)
|
||||||
|
} else {
|
||||||
|
Err(format!("{name} {number} is refused: it must be {} to {}", range.start(), range.end()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The place or institution `text` names, by the id `table_view` prints.
|
||||||
|
fn resolve(text: &str, world: &WorldSnapshot) -> Result<Target, String> {
|
||||||
|
if let Some(place) = world.places.iter().find(|place| id_text_matches(place.id, text)) {
|
||||||
|
return Ok(Target::Place(place.id));
|
||||||
|
}
|
||||||
|
match world.subjects.iter().find(|subject| id_text_matches(subject.id, text)) {
|
||||||
|
Some(subject) if subject.kind == SubjectKind::Institution && !subject.retired => {
|
||||||
|
Ok(Target::Institution(subject.id))
|
||||||
|
}
|
||||||
|
Some(subject) => Err(format!(
|
||||||
|
"`{text}` names {}, which is not an institution; name its place or its institution",
|
||||||
|
subject.label
|
||||||
|
)),
|
||||||
|
None => Err(format!("`{text}` names no place or institution in the world")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn arguments_object(arguments: &str, tool: &str) -> Result<serde_json::Map<String, Value>, String> {
|
||||||
|
match serde_json::from_str::<Value>(arguments) {
|
||||||
|
Ok(Value::Object(fields)) => Ok(fields),
|
||||||
|
_ => Err(format!("{tool}'s arguments are not a JSON object: `{arguments}`")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn texts(name: &str, value: &Value) -> Result<Vec<String>, String> {
|
||||||
|
let Some(items) = value.as_array() else {
|
||||||
|
return Err(format!("{name} must be a list, got {value}"));
|
||||||
|
};
|
||||||
|
items
|
||||||
|
.iter()
|
||||||
|
.map(|item| item.as_str().map(str::to_owned).ok_or_else(|| format!("{name} holds {item}, which is not an id")))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `tune`'s arguments applied to `current` at fictional minute `now`: the new
|
||||||
|
/// knobs and what changed, or the refusal naming the first value outside its
|
||||||
|
/// bound. Nothing changes unless every value is admitted.
|
||||||
|
pub(crate) fn tune(
|
||||||
|
current: &DmKnobs,
|
||||||
|
arguments: &str,
|
||||||
|
world: &WorldSnapshot,
|
||||||
|
now: u64,
|
||||||
|
) -> Result<(DmKnobs, String), String> {
|
||||||
|
let fields = arguments_object(arguments, "tune")?;
|
||||||
|
let mut next = current.clone();
|
||||||
|
next.focus.retain(|lease| lease.until > now);
|
||||||
|
let mut changed = Vec::new();
|
||||||
|
for (name, value) in &fields {
|
||||||
|
match name.as_str() {
|
||||||
|
"bands" => {
|
||||||
|
let items = value.as_array().ok_or_else(|| format!("bands must be a list, got {value}"))?;
|
||||||
|
if items.is_empty() || items.len() > MOST_BANDS {
|
||||||
|
return Err(format!("bands holds {} periods, refused: it takes 1 to {MOST_BANDS}", items.len()));
|
||||||
|
}
|
||||||
|
next.knobs.bands = items
|
||||||
|
.iter()
|
||||||
|
.map(|item| whole("band", item, 1..=LONGEST_MINUTES).map(|minutes| minutes as u32))
|
||||||
|
.collect::<Result<_, _>>()?;
|
||||||
|
changed.push(format!("bands {:?} minutes", next.knobs.bands));
|
||||||
|
}
|
||||||
|
"depth" => {
|
||||||
|
next.knobs.depth = whole("depth", value, DEPTHS)? as u8;
|
||||||
|
changed.push(format!("depth {}", next.knobs.depth));
|
||||||
|
}
|
||||||
|
"max_node_turns" => {
|
||||||
|
next.knobs.max_node_turns = whole("max_node_turns", value, NODE_TURNS)? as u16;
|
||||||
|
changed.push(format!("max_node_turns {}", next.knobs.max_node_turns));
|
||||||
|
}
|
||||||
|
"wave_allowance" => {
|
||||||
|
next.allowances.wave = whole("wave_allowance", value, 0..=MOST_ALLOWANCE)? as u64;
|
||||||
|
changed.push(format!("wave allowance {} tokens", next.allowances.wave));
|
||||||
|
}
|
||||||
|
"elaboration_allowance" => {
|
||||||
|
next.allowances.elaboration = whole("elaboration_allowance", value, 0..=MOST_ALLOWANCE)? as u64;
|
||||||
|
changed.push(format!("elaboration allowance {} tokens", next.allowances.elaboration));
|
||||||
|
}
|
||||||
|
"focus_remove" => {
|
||||||
|
for text in texts("focus_remove", value)? {
|
||||||
|
let before = next.focus.len();
|
||||||
|
next.focus.retain(|lease| lease.target.text() != text);
|
||||||
|
if next.focus.len() == before {
|
||||||
|
return Err(format!("`{text}` is not one of your focus entries"));
|
||||||
|
}
|
||||||
|
changed.push(format!("focus on {text} removed"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"focus_add" => {}
|
||||||
|
other => return Err(format!("tune takes no `{other}`")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(value) = fields.get("focus_add") {
|
||||||
|
let items = value.as_array().ok_or_else(|| format!("focus_add must be a list, got {value}"))?;
|
||||||
|
for item in items {
|
||||||
|
let entry = item.as_object().ok_or_else(|| format!("focus_add holds {item}, which is not an entry"))?;
|
||||||
|
let text = entry
|
||||||
|
.get("target")
|
||||||
|
.and_then(Value::as_str)
|
||||||
|
.ok_or_else(|| format!("focus_add entry {item} names no target"))?;
|
||||||
|
let minutes = whole("lease_minutes", entry.get("lease_minutes").unwrap_or(&Value::Null), 1..=LONGEST_MINUTES)?;
|
||||||
|
let target = resolve(text, world)?;
|
||||||
|
next.focus.retain(|lease| lease.target != target);
|
||||||
|
next.focus.push(Lease { target, until: now.saturating_add(minutes as u64) });
|
||||||
|
changed.push(format!("focus on {text} for {minutes} minutes"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if changed.is_empty() {
|
||||||
|
return Err("tune changed nothing: name bands, depth, max_node_turns, wave_allowance, elaboration_allowance, focus_add or focus_remove".into());
|
||||||
|
}
|
||||||
|
if next.focus.len() > MOST_ENTRIES {
|
||||||
|
return Err(format!("{} focus entries is refused: {MOST_ENTRIES} at most", next.focus.len()));
|
||||||
|
}
|
||||||
|
next.gestalt().map_err(|error| error.to_string())?;
|
||||||
|
Ok((next, format!("tuned: {}. Allowances bind the window already open too: a lane held above its new allowance is exhausted.", changed.join("; "))))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `run_world`'s arguments: the targets it names, resolved against the world.
|
||||||
|
pub(crate) fn run_world(arguments: &str, world: &WorldSnapshot) -> Result<Vec<Target>, String> {
|
||||||
|
let fields = arguments_object(arguments, "run_world")?;
|
||||||
|
let value = fields.get("targets").ok_or_else(|| format!("run_world needs `targets`: `{arguments}`"))?;
|
||||||
|
let mut targets = Vec::new();
|
||||||
|
for text in texts("targets", value)? {
|
||||||
|
let target = resolve(&text, world)?;
|
||||||
|
if !targets.contains(&target) {
|
||||||
|
targets.push(target);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if targets.is_empty() || targets.len() > MOST_ENTRIES {
|
||||||
|
return Err(format!("run_world takes 1 to {MOST_ENTRIES} targets, got {}", targets.len()));
|
||||||
|
}
|
||||||
|
Ok(targets)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Average tokens a node turn cost, by band, from the waves the timeline has
|
||||||
|
/// closed: `(average, node turns)` for each band, the last band taking every
|
||||||
|
/// distance beyond it.
|
||||||
|
pub(crate) fn band_costs(nodes: impl Iterator<Item = (u8, u64)>, bands: usize) -> Vec<(u64, u64)> {
|
||||||
|
let mut totals = vec![(0u64, 0u64); bands];
|
||||||
|
for (distance, tokens) in nodes {
|
||||||
|
let band = usize::from(distance).min(bands - 1);
|
||||||
|
totals[band].0 += tokens;
|
||||||
|
totals[band].1 += 1;
|
||||||
|
}
|
||||||
|
totals
|
||||||
|
.into_iter()
|
||||||
|
.map(|(tokens, turns)| (tokens.checked_div(turns).unwrap_or(0), turns))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The section of the DM's opening view that shows its gears: the knobs, where
|
||||||
|
/// attention is, what is queued and what each band has cost.
|
||||||
|
pub(crate) fn gears_view(
|
||||||
|
knobs: &DmKnobs,
|
||||||
|
world: &WorldSnapshot,
|
||||||
|
hierarchy: &Hierarchy,
|
||||||
|
player_places: &[EntityId],
|
||||||
|
costs: &[(u64, u64)],
|
||||||
|
) -> String {
|
||||||
|
let mut out = String::from(
|
||||||
|
"The world beyond the room, and the gears you may turn (`tune`, `run_world`; time stays yours, and nothing here runs a node that is not due unless you ask):\n",
|
||||||
|
);
|
||||||
|
let bands: Vec<String> = knobs.knobs.bands.iter().map(u32::to_string).collect();
|
||||||
|
out.push_str(&format!(
|
||||||
|
"- Bands, minutes between a node's turns by distance from the focus, nearest first: {}. Depth {} (nodes open along each focus path), at most {} node turns a wave.\n",
|
||||||
|
bands.join(", "),
|
||||||
|
knobs.knobs.depth,
|
||||||
|
knobs.knobs.max_node_turns
|
||||||
|
));
|
||||||
|
out.push_str(&format!(
|
||||||
|
"- Allowances in one post-turn window: wave {} tokens, elaboration {} tokens.\n",
|
||||||
|
knobs.allowances.wave, knobs.allowances.elaboration
|
||||||
|
));
|
||||||
|
for place in player_places {
|
||||||
|
let path: Vec<String> = hierarchy.focus_path(*place).into_iter().map(|node| node_label(node, world, hierarchy)).collect();
|
||||||
|
out.push_str(&format!("- The player's focus runs {}.\n", path.join(" > ")));
|
||||||
|
}
|
||||||
|
for lease in knobs.standing(world.now.0) {
|
||||||
|
out.push_str(&format!(
|
||||||
|
"- Your focus: {} [{}], {} more minutes.\n",
|
||||||
|
target_label(&lease.target, world),
|
||||||
|
lease.target.text(),
|
||||||
|
lease.until - world.now.0
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if !knobs.forced.is_empty() {
|
||||||
|
let named: Vec<String> = knobs.forced.iter().map(|target| target_label(target, world)).collect();
|
||||||
|
out.push_str(&format!("- Asked to run in this turn's wave: {}.\n", named.join(", ")));
|
||||||
|
}
|
||||||
|
let spent: Vec<String> = costs
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(band, (average, turns))| {
|
||||||
|
if *turns == 0 {
|
||||||
|
format!("band {band}: no node turn yet")
|
||||||
|
} else {
|
||||||
|
format!("band {band}: {average} tokens over {turns} node turns")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
out.push_str(&format!("- What a node turn has cost on average: {}.\n\n", spent.join("; ")));
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn target_label(target: &Target, world: &WorldSnapshot) -> String {
|
||||||
|
match target {
|
||||||
|
Target::Place(id) => world.places.iter().find(|place| place.id == *id).map(|place| place.label.clone()),
|
||||||
|
Target::Institution(id) => world.subjects.iter().find(|subject| subject.id == *id).map(|subject| subject.label.clone()),
|
||||||
|
}
|
||||||
|
.unwrap_or_else(|| "-".to_owned())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::{play::tests::ScriptedPort, waves::tests::Fixture};
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
fn opaque<T: serde::de::DeserializeOwned>() -> T {
|
||||||
|
serde_json::from_value(json!(uuid::Uuid::new_v4().to_string())).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A world with a player, a Warden and two places, and the id of each place.
|
||||||
|
async fn world() -> (WorldSnapshot, Hierarchy, EntityId, EntityId) {
|
||||||
|
let fixture = Fixture::new().await;
|
||||||
|
let (timelines, _stopped) = fixture.open(ScriptedPort::new(vec![]));
|
||||||
|
let host = timelines.host(&fixture.id).await.unwrap();
|
||||||
|
let world = host.world.snapshot().await.unwrap();
|
||||||
|
let hierarchy = host.world.hierarchy().await.unwrap();
|
||||||
|
let place = |label: &str| world.places.iter().find(|place| place.label == label).unwrap().id;
|
||||||
|
let (commons, gate) = (place("The Commons"), place("Gatehouse"));
|
||||||
|
(world, hierarchy, commons, gate)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The same world with `count` more places declared, and every place's id.
|
||||||
|
async fn crowded_world(count: usize) -> (WorldSnapshot, Vec<EntityId>) {
|
||||||
|
let fixture = Fixture::new().await;
|
||||||
|
let (timelines, _stopped) = fixture.open(ScriptedPort::new(vec![]));
|
||||||
|
let host = timelines.host(&fixture.id).await.unwrap();
|
||||||
|
let declared: Vec<String> = (0..count)
|
||||||
|
.map(|number| json!({"handle": format!("p{number}"), "label": format!("Place {number}"), "container": null}).to_string())
|
||||||
|
.collect();
|
||||||
|
let calls: Vec<(&str, &str)> = declared.iter().map(|call| ("declare_place", call.as_str())).collect();
|
||||||
|
let decoded = ghostlight::decode_authoring_calls(&calls).unwrap();
|
||||||
|
ghostlight::PlayPort::new(host.world.clone())
|
||||||
|
.submit_patch(ghostlight::CommandId::new(), decoded.patch)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let world = host.world.snapshot().await.unwrap();
|
||||||
|
let places = world.places.iter().map(|place| place.id).collect();
|
||||||
|
(world, places)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn refusal(current: &DmKnobs, world: &WorldSnapshot, arguments: serde_json::Value) -> String {
|
||||||
|
tune(current, &arguments.to_string(), world, 0).expect_err("the call is refused")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Spec test `bad values refused`: a value outside its bound is refused
|
||||||
|
/// whole, quoting the value, and a refused call leaves the document as it was.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_value_outside_its_bound_is_refused_quoting_it() {
|
||||||
|
let (world, _, commons, _) = world().await;
|
||||||
|
let current = DmKnobs::default();
|
||||||
|
assert!(refusal(¤t, &world, json!({"bands": [60, -5]})).contains("band -5"));
|
||||||
|
assert!(refusal(¤t, &world, json!({"bands": [0]})).contains("band 0"));
|
||||||
|
assert!(refusal(¤t, &world, json!({"bands": [525_601]})).contains("band 525601"));
|
||||||
|
assert!(refusal(¤t, &world, json!({"bands": []})).contains("0 periods"));
|
||||||
|
assert!(refusal(¤t, &world, json!({"bands": [1, 2, 3, 4, 5, 6, 7, 8, 9]})).contains("9 periods"));
|
||||||
|
assert!(refusal(¤t, &world, json!({"depth": 0})).contains("depth 0"));
|
||||||
|
assert!(refusal(¤t, &world, json!({"depth": 9})).contains("depth 9"));
|
||||||
|
assert!(refusal(¤t, &world, json!({"depth": "deep"})).contains("\"deep\""));
|
||||||
|
assert!(refusal(¤t, &world, json!({"depth": 2.5})).contains("2.5"));
|
||||||
|
assert!(refusal(¤t, &world, json!({"max_node_turns": 0})).contains("max_node_turns 0"));
|
||||||
|
assert!(refusal(¤t, &world, json!({"max_node_turns": 33})).contains("max_node_turns 33"));
|
||||||
|
assert!(refusal(¤t, &world, json!({"wave_allowance": -1})).contains("wave_allowance -1"));
|
||||||
|
assert!(refusal(¤t, &world, json!({"elaboration_allowance": 5_000_001})).contains("5000001"));
|
||||||
|
assert!(refusal(¤t, &world, json!({"focus_remove": [id_text(commons)]})).contains("not one of your focus entries"));
|
||||||
|
let lease = |minutes: i64| json!({"focus_add": [{"target": id_text(commons), "lease_minutes": minutes}]});
|
||||||
|
assert!(refusal(¤t, &world, lease(0)).contains("lease_minutes 0"));
|
||||||
|
assert!(refusal(¤t, &world, lease(525_601)).contains("lease_minutes 525601"));
|
||||||
|
assert!(refusal(¤t, &world, json!({"focus_add": [{"target": id_text(commons)}]})).contains("lease_minutes"));
|
||||||
|
assert!(refusal(¤t, &world, json!({"focus_add": [{"target": "nowhere", "lease_minutes": 5}]})).contains("`nowhere`"));
|
||||||
|
assert!(refusal(¤t, &world, json!({"depth": 3, "colour": "red"})).contains("`colour`"), "an unknown field is refused");
|
||||||
|
assert!(refusal(¤t, &world, json!({})).contains("changed nothing"));
|
||||||
|
assert!(tune(¤t, "[1]", &world, 0).unwrap_err().contains("not a JSON object"));
|
||||||
|
let person = id_text(world.subjects.iter().find(|subject| subject.label == "Player").unwrap().id);
|
||||||
|
assert!(refusal(¤t, &world, json!({"focus_add": [{"target": person, "lease_minutes": 5}]})).contains("not an institution"));
|
||||||
|
// One good field beside a bad one changes nothing: the call is refused whole.
|
||||||
|
assert!(tune(¤t, r#"{"depth": 4, "bands": [-1]}"#, &world, 0).is_err());
|
||||||
|
assert_eq!(current, DmKnobs::default());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The values inside their bounds are applied, a lease is anchored at the
|
||||||
|
/// clock the call was made at, and a lease the DM re-adds replaces its own.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_tune_inside_its_bounds_applies_every_field() {
|
||||||
|
let (world, _, commons, gate) = world().await;
|
||||||
|
let current = DmKnobs::default();
|
||||||
|
let asked = json!({
|
||||||
|
"bands": [5, 525_600],
|
||||||
|
"depth": 8,
|
||||||
|
"max_node_turns": 32,
|
||||||
|
"wave_allowance": 0,
|
||||||
|
"elaboration_allowance": 5_000_000,
|
||||||
|
"focus_add": [{"target": id_text(gate), "lease_minutes": 30}],
|
||||||
|
});
|
||||||
|
let eight = json!({"bands": [1, 2, 3, 4, 5, 6, 7, 8]});
|
||||||
|
assert_eq!(tune(¤t, &eight.to_string(), &world, 0).unwrap().0.knobs.bands.len(), 8, "eight periods is the most");
|
||||||
|
let (next, said) = tune(¤t, &asked.to_string(), &world, 100).unwrap();
|
||||||
|
assert_eq!(next.knobs.bands, vec![5, 525_600]);
|
||||||
|
assert_eq!((next.knobs.depth, next.knobs.max_node_turns), (8, 32));
|
||||||
|
assert_eq!(next.allowances, LaneTokens { wave: 0, elaboration: 5_000_000 });
|
||||||
|
assert_eq!(next.focus, vec![Lease { target: Target::Place(gate), until: 130 }]);
|
||||||
|
assert_eq!(next.knobs.cells, current.knobs.cells, "the cover is not the DM\'s to tune");
|
||||||
|
assert!(said.contains("depth 8") && said.contains("open too"), "{said}");
|
||||||
|
|
||||||
|
let again = json!({"focus_add": [{"target": id_text(gate), "lease_minutes": 10}]});
|
||||||
|
let (renewed, _) = tune(&next, &again.to_string(), &world, 110).unwrap();
|
||||||
|
assert_eq!(renewed.focus, vec![Lease { target: Target::Place(gate), until: 120 }]);
|
||||||
|
let (swapped, _) = tune(&renewed, &json!({"focus_remove": [id_text(gate)]}).to_string(), &world, 111).unwrap();
|
||||||
|
assert!(swapped.focus.is_empty());
|
||||||
|
let (dropped, _) = tune(&next, &json!({"depth": 1}).to_string(), &world, 130).unwrap();
|
||||||
|
assert!(dropped.focus.is_empty(), "a lapsed lease is dropped by the next tune");
|
||||||
|
let two = json!({"focus_add": [{"target": id_text(commons), "lease_minutes": 5}, {"target": id_text(gate), "lease_minutes": 5}]});
|
||||||
|
assert_eq!(tune(¤t, &two.to_string(), &world, 0).unwrap().0.focus.len(), 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Eight focus entries are the most: the ninth is refused whole, and an
|
||||||
|
/// entry the DM already holds is renewed, not added.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn the_document_holds_eight_focus_entries_and_no_more() {
|
||||||
|
let (world, places) = crowded_world(8).await;
|
||||||
|
let asked = |place: EntityId| json!({"focus_add": [{"target": id_text(place), "lease_minutes": 30}]}).to_string();
|
||||||
|
let mut doc = DmKnobs::default();
|
||||||
|
for place in &places[..8] {
|
||||||
|
doc = tune(&doc, &asked(*place), &world, 0).unwrap().0;
|
||||||
|
}
|
||||||
|
assert_eq!(doc.focus.len(), 8, "eight entries are admitted");
|
||||||
|
assert!(tune(&doc, &asked(places[8]), &world, 0).unwrap_err().contains("9 focus entries"));
|
||||||
|
assert_eq!(tune(&doc, &asked(places[0]), &world, 5).unwrap().0.focus.len(), 8, "renewing is not adding");
|
||||||
|
assert_eq!(tune(&doc, &asked(places[8]), &world, 30).unwrap().0.focus.len(), 1, "lapsed entries make room");
|
||||||
|
let named = |count: usize| {
|
||||||
|
let ids: Vec<String> = places[..count].iter().map(|place| id_text(*place)).collect();
|
||||||
|
run_world(&json!({"targets": ids}).to_string(), &world)
|
||||||
|
};
|
||||||
|
assert_eq!(named(8).unwrap().len(), 8);
|
||||||
|
assert!(named(9).unwrap_err().contains("got 9"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An institution is named like a place and is the DM's focus or ask; a
|
||||||
|
/// person is not.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn an_institution_is_named_by_its_id_and_labelled_by_its_name() {
|
||||||
|
let (mut world, hierarchy, _, _) = world().await;
|
||||||
|
let warden = world.subjects.iter().find(|subject| subject.label == "Warden").unwrap().id;
|
||||||
|
let asked = json!({"focus_add": [{"target": id_text(warden), "lease_minutes": 30}]}).to_string();
|
||||||
|
let (doc, _) = tune(&DmKnobs::default(), &asked, &world, 0).unwrap();
|
||||||
|
assert_eq!(doc.focus, vec![Lease { target: Target::Institution(warden), until: 30 }]);
|
||||||
|
assert_eq!(run_world(&json!({"targets": [id_text(warden)]}).to_string(), &world).unwrap(), vec![Target::Institution(warden)]);
|
||||||
|
let mut retired = world.clone();
|
||||||
|
retired.subjects.iter_mut().find(|subject| subject.id == warden).unwrap().retired = true;
|
||||||
|
assert!(tune(&DmKnobs::default(), &asked, &retired, 0).unwrap_err().contains("not an institution"), "a retired institution is not named");
|
||||||
|
world.now = ghostlight::FictionalMinutes(0);
|
||||||
|
let view = gears_view(&doc, &world, &hierarchy, &[], &[(0, 0)]);
|
||||||
|
assert!(view.contains(&format!("Your focus: Warden [{}], 30 more minutes.", id_text(warden))), "{view}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn run_world_names_places_and_institutions_the_view_prints() {
|
||||||
|
let (world, _, commons, gate) = world().await;
|
||||||
|
let named = |ids: Vec<String>| run_world(&json!({"targets": ids}).to_string(), &world);
|
||||||
|
assert_eq!(
|
||||||
|
named(vec![id_text(gate), id_text(commons), id_text(gate)]).unwrap(),
|
||||||
|
vec![Target::Place(gate), Target::Place(commons)],
|
||||||
|
"each target once, in the order named"
|
||||||
|
);
|
||||||
|
assert!(named(vec![]).unwrap_err().contains("1 to 8 targets"));
|
||||||
|
assert!(named(vec!["nowhere".into()]).unwrap_err().contains("`nowhere`"));
|
||||||
|
assert!(run_world("{}", &world).unwrap_err().contains("needs `targets`"));
|
||||||
|
assert!(run_world(r#"{"targets":"all"}"#, &world).unwrap_err().contains("must be a list"));
|
||||||
|
assert!(run_world(r#"{"targets":[3]}"#, &world).unwrap_err().contains("not an id"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A target is the node that governs it: a place's governing node, an
|
||||||
|
/// institution's own, none for an institution the world no longer holds.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_target_is_the_node_that_governs_it() {
|
||||||
|
let (world, hierarchy, commons, gate) = world().await;
|
||||||
|
let anchor = |target: Target| hierarchy.nodes[&target.node(&hierarchy).unwrap()].anchor;
|
||||||
|
assert_eq!(anchor(Target::Place(commons)), NodeAnchor::Place(commons));
|
||||||
|
assert_eq!(anchor(Target::Place(gate)), NodeAnchor::Place(gate));
|
||||||
|
let warden = world.subjects.iter().find(|subject| subject.label == "Warden").unwrap().id;
|
||||||
|
assert_eq!(anchor(Target::Institution(warden)), NodeAnchor::Institution(warden));
|
||||||
|
assert_eq!(Target::Institution(opaque::<SubjectId>()).node(&hierarchy), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_stored_document_is_the_one_a_reopen_reads() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let path = directory.path().join("gestalt-knobs.cc");
|
||||||
|
let mut kept = DmKnobs::default();
|
||||||
|
{
|
||||||
|
let mut store = KnobStore::open(&path).unwrap();
|
||||||
|
assert_eq!(store.current(), DmKnobs::default(), "a Begin\'s knobs, written at first open");
|
||||||
|
kept.knobs.depth = 5;
|
||||||
|
kept.focus.push(Lease { target: Target::Place(opaque::<EntityId>()), until: 9 });
|
||||||
|
kept.forced.push(Target::Institution(opaque::<SubjectId>()));
|
||||||
|
store.replace(kept.clone()).unwrap();
|
||||||
|
}
|
||||||
|
assert_eq!(KnobStore::open(&path).unwrap().current(), kept);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_document_the_planner_would_refuse_is_not_opened() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let path = directory.path().join("gestalt-knobs.cc");
|
||||||
|
{
|
||||||
|
let mut store = KnobStore::open(&path).unwrap();
|
||||||
|
let mut broken = DmKnobs::default();
|
||||||
|
broken.knobs.bands.clear();
|
||||||
|
store.replace(broken).unwrap();
|
||||||
|
}
|
||||||
|
assert!(KnobStore::open(&path).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a band costs on average is read from the node turns the closed waves
|
||||||
|
/// report: a distance past the last band is the last band.
|
||||||
|
#[test]
|
||||||
|
fn a_bands_cost_is_the_average_of_its_node_turns() {
|
||||||
|
let turns = [(0u8, 100u64), (0, 300), (1, 50), (9, 10), (3, 30)];
|
||||||
|
assert_eq!(band_costs(turns.into_iter(), 3), vec![(200, 2), (50, 1), (20, 2)]);
|
||||||
|
assert_eq!(band_costs(std::iter::empty(), 2), vec![(0, 0), (0, 0)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn the_view_prints_the_gears_where_attention_is_and_what_is_asked() {
|
||||||
|
let (mut world, hierarchy, commons, gate) = world().await;
|
||||||
|
world.now = ghostlight::FictionalMinutes(10);
|
||||||
|
let mut knobs = DmKnobs::default();
|
||||||
|
knobs.focus = vec![
|
||||||
|
Lease { target: Target::Place(gate), until: 70 },
|
||||||
|
Lease { target: Target::Place(commons), until: 10 },
|
||||||
|
];
|
||||||
|
knobs.forced = vec![Target::Place(gate)];
|
||||||
|
let view = gears_view(&knobs, &world, &hierarchy, &[commons], &[(200, 2), (0, 0), (0, 0), (0, 0)]);
|
||||||
|
assert!(view.contains("60, 360, 1440, 10080. Depth 2"), "{view}");
|
||||||
|
assert!(view.contains("wave 200000 tokens, elaboration 200000 tokens"));
|
||||||
|
assert!(view.contains("The player\'s focus runs The Commons > world."));
|
||||||
|
assert!(view.contains(&format!("Your focus: Gatehouse [{}], 60 more minutes.", id_text(gate))));
|
||||||
|
assert!(!view.contains("Your focus: The Commons"), "a lapsed lease is not shown");
|
||||||
|
assert!(view.contains("Asked to run in this turn\'s wave: Gatehouse."));
|
||||||
|
assert!(view.contains("band 0: 200 tokens over 2 node turns; band 1: no node turn yet"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,10 +1,27 @@
|
||||||
|
mod api;
|
||||||
mod app_session;
|
mod app_session;
|
||||||
mod eve;
|
mod auth_guard;
|
||||||
|
mod begin;
|
||||||
|
mod catalog;
|
||||||
mod heimdall;
|
mod heimdall;
|
||||||
mod idunn_health;
|
mod idunn_health;
|
||||||
mod mesh;
|
mod invite;
|
||||||
|
mod knobs;
|
||||||
|
mod page;
|
||||||
|
#[cfg(test)]
|
||||||
|
mod playtest;
|
||||||
mod play;
|
mod play;
|
||||||
|
mod run_ahead;
|
||||||
mod runtime;
|
mod runtime;
|
||||||
|
mod session_refresh;
|
||||||
|
mod state_layout;
|
||||||
|
#[cfg(test)]
|
||||||
|
mod test_support;
|
||||||
|
mod timelines;
|
||||||
|
mod turn_log;
|
||||||
|
mod vaults;
|
||||||
|
mod verbs;
|
||||||
|
mod waves;
|
||||||
|
|
||||||
use anyhow::bail;
|
use anyhow::bail;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
@ -13,9 +30,18 @@ use std::path::PathBuf;
|
||||||
async fn main() -> anyhow::Result<()> {
|
async fn main() -> anyhow::Result<()> {
|
||||||
let args = std::env::args_os().skip(1).collect::<Vec<_>>();
|
let args = std::env::args_os().skip(1).collect::<Vec<_>>();
|
||||||
let state_root = match args.as_slice() {
|
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)),
|
[flag, path] if flag == "--state-root" => Some(PathBuf::from(path)),
|
||||||
[] => None,
|
[] => None,
|
||||||
_ => bail!("usage: ghostlight-dungeon [--state-root PATH]"),
|
_ => 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
|
runtime::run(state_root).await
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,464 +0,0 @@
|
||||||
//! Derived CultMesh and Eve projection.
|
|
||||||
//!
|
|
||||||
//! The mesh publishes the world owner's current surface. It never pulls or
|
|
||||||
//! repairs world state and it has no command authority.
|
|
||||||
|
|
||||||
use crate::eve;
|
|
||||||
use ghostlight::{CONSUMER_PATCH_SCHEMA, CONSUMER_RECEIPT_SCHEMA, STATE_SCHEMA, WorldSnapshot};
|
|
||||||
use anyhow::Result;
|
|
||||||
use chrono::{DateTime, Utc};
|
|
||||||
use cultcache_rs::DatabaseEntry;
|
|
||||||
use cultmesh_rs::{
|
|
||||||
CultMesh, CultMeshNode, CultMeshNodeOptions, CultMeshRudpDocumentPublishOptions,
|
|
||||||
publish_cultnet_messages_to_rudp_catalog,
|
|
||||||
};
|
|
||||||
use serde_json::{Value, json};
|
|
||||||
use std::{
|
|
||||||
net::SocketAddr,
|
|
||||||
path::Path,
|
|
||||||
sync::{
|
|
||||||
Arc, Condvar, Mutex,
|
|
||||||
atomic::{AtomicBool, Ordering},
|
|
||||||
},
|
|
||||||
thread,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub(crate) const PROVIDER_ID: &str = "gamecult.ghostlight.dungeon";
|
|
||||||
pub(crate) const SURFACE_ID: &str = "ghostlight.play";
|
|
||||||
pub(crate) const COMMAND_BOUNDARY: &str = "ghostlight.eve.commands";
|
|
||||||
pub(crate) const COMMAND_RESULT_SCHEMA: &str = "gamecult.eve.command_result.v1";
|
|
||||||
pub(crate) const COMMAND_RECEIPT_SCHEMA: &str = "gamecult.eve.command_receipt.v1";
|
|
||||||
/// The repository that owns this surface, as the command receipt contract
|
|
||||||
/// requires of every result.
|
|
||||||
pub(crate) const OWNER_REPO: &str = "GameCult/Ghostlight";
|
|
||||||
|
|
||||||
const HEALTH_KEY: &str = "ghostlight:dungeon:health";
|
|
||||||
const ADVERTISEMENT_KEY: &str = "eve:provider:gamecult.ghostlight.dungeon";
|
|
||||||
const SURFACE_KEY: &str = "eve:surface:ghostlight.play";
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
|
|
||||||
#[cultcache(type = "gamecult.eve.surface", schema = "gamecult.eve.surface.v1")]
|
|
||||||
struct EveSurfaceRecord {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
value: Value,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
|
|
||||||
#[cultcache(
|
|
||||||
type = "gamecult.eve.provider_advertisement",
|
|
||||||
schema = "gamecult.eve.provider_advertisement.v1"
|
|
||||||
)]
|
|
||||||
struct EveProviderAdvertisementRecord {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
value: Value,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
|
|
||||||
#[cultcache(
|
|
||||||
type = "ghostlight.service_health",
|
|
||||||
schema = "ghostlight.service_health.v2"
|
|
||||||
)]
|
|
||||||
struct ServiceHealthRecord {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
value: Value,
|
|
||||||
}
|
|
||||||
|
|
||||||
cultmesh_rs::cultmesh_documents!(GhostlightDocuments {
|
|
||||||
EveSurfaceRecord => "gamecult.eve.surface.v1",
|
|
||||||
EveProviderAdvertisementRecord => "gamecult.eve.provider_advertisement.v1",
|
|
||||||
ServiceHealthRecord => "ghostlight.service_health.v2",
|
|
||||||
});
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub(crate) struct MeshRuntimeIdentity {
|
|
||||||
pub(crate) runtime_id: String,
|
|
||||||
pub(crate) service_id: String,
|
|
||||||
pub(crate) located_service: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for MeshRuntimeIdentity {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self {
|
|
||||||
runtime_id: "ghostlight-dungeon".into(),
|
|
||||||
service_id: "ghostlight-dungeon".into(),
|
|
||||||
located_service: "local".into(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub(crate) struct MeshPublisher {
|
|
||||||
node: Arc<Mutex<CultMeshNode>>,
|
|
||||||
remote: Option<RemoteReplication>,
|
|
||||||
identity: MeshRuntimeIdentity,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
struct RemoteReplication {
|
|
||||||
target: SocketAddr,
|
|
||||||
runtime_id: String,
|
|
||||||
pending: Arc<(Mutex<Option<Vec<cultnet_rs::CultNetMessage>>>, Condvar)>,
|
|
||||||
alive: Arc<AtomicBool>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl MeshPublisher {
|
|
||||||
pub(crate) fn open(
|
|
||||||
store_path: impl AsRef<Path>,
|
|
||||||
rudp_target: Option<SocketAddr>,
|
|
||||||
identity: MeshRuntimeIdentity,
|
|
||||||
) -> Result<Self> {
|
|
||||||
if let Some(parent) = store_path.as_ref().parent() {
|
|
||||||
std::fs::create_dir_all(parent)?;
|
|
||||||
}
|
|
||||||
let node = CultMesh::create_node(
|
|
||||||
store_path,
|
|
||||||
GhostlightDocuments,
|
|
||||||
CultMeshNodeOptions {
|
|
||||||
runtime_id: identity.runtime_id.clone(),
|
|
||||||
// Ghostlight derives its own interface from the local owner.
|
|
||||||
// Stale remote surfaces must never become startup authority.
|
|
||||||
pull_on_start: false,
|
|
||||||
},
|
|
||||||
)?;
|
|
||||||
let remote = rudp_target
|
|
||||||
.map(|target| RemoteReplication::start(target, identity.runtime_id.clone()))
|
|
||||||
.transpose()?;
|
|
||||||
Ok(Self {
|
|
||||||
node: Arc::new(Mutex::new(node)),
|
|
||||||
remote,
|
|
||||||
identity,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn provider_advertisement(&self, updated_at: &str) -> Value {
|
|
||||||
provider_advertisement(&self.identity, updated_at)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn publish(&self, snapshot: Option<&WorldSnapshot>) -> Result<Value> {
|
|
||||||
let surface = eve::mesh_surface(snapshot);
|
|
||||||
let world_state = eve::world_state(snapshot);
|
|
||||||
let version = eve::surface_version(snapshot);
|
|
||||||
let updated_at = Utc::now().to_rfc3339();
|
|
||||||
let health = json!({
|
|
||||||
"schema":"ghostlight.service_health.v2",
|
|
||||||
"status":"ok",
|
|
||||||
"worldState":world_state,
|
|
||||||
"surfaceVersion":version,
|
|
||||||
"updatedAtUtc":updated_at,
|
|
||||||
"runtime":self.identity.runtime_id,
|
|
||||||
"commit":option_env!("GHOSTLIGHT_BUILD_COMMIT").unwrap_or("development")
|
|
||||||
});
|
|
||||||
let advertisement = provider_advertisement(&self.identity, &updated_at);
|
|
||||||
let mut node = self
|
|
||||||
.node
|
|
||||||
.lock()
|
|
||||||
.map_err(|_| anyhow::anyhow!("mesh lock poisoned"))?;
|
|
||||||
let mut remote_messages = Vec::new();
|
|
||||||
self.put_and_stage(
|
|
||||||
&mut node,
|
|
||||||
ADVERTISEMENT_KEY,
|
|
||||||
&EveProviderAdvertisementRecord {
|
|
||||||
value: advertisement,
|
|
||||||
},
|
|
||||||
&mut remote_messages,
|
|
||||||
)?;
|
|
||||||
self.put_and_stage(
|
|
||||||
&mut node,
|
|
||||||
SURFACE_KEY,
|
|
||||||
&EveSurfaceRecord { value: surface },
|
|
||||||
&mut remote_messages,
|
|
||||||
)?;
|
|
||||||
// Health is the completion marker for this derived projection. A
|
|
||||||
// failed advertisement or surface write must leave the prior version
|
|
||||||
// visibly stale rather than publishing green first.
|
|
||||||
self.put_and_stage(
|
|
||||||
&mut node,
|
|
||||||
HEALTH_KEY,
|
|
||||||
&ServiceHealthRecord {
|
|
||||||
value: health.clone(),
|
|
||||||
},
|
|
||||||
&mut remote_messages,
|
|
||||||
)?;
|
|
||||||
drop(node);
|
|
||||||
if let Some(remote) = &self.remote {
|
|
||||||
remote.enqueue(remote_messages);
|
|
||||||
}
|
|
||||||
Ok(health)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn health(&self) -> Result<Value> {
|
|
||||||
if self
|
|
||||||
.remote
|
|
||||||
.as_ref()
|
|
||||||
.is_some_and(|remote| !remote.is_alive())
|
|
||||||
{
|
|
||||||
anyhow::bail!("Odin projection worker stopped");
|
|
||||||
}
|
|
||||||
self.node
|
|
||||||
.try_lock()
|
|
||||||
.map_err(|_| anyhow::anyhow!("mesh projection is busy or its lock is poisoned"))?
|
|
||||||
.get_required::<ServiceHealthRecord>(HEALTH_KEY)
|
|
||||||
.map(|record| record.value)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn put_and_stage<T>(
|
|
||||||
&self,
|
|
||||||
node: &mut CultMeshNode,
|
|
||||||
key: impl Into<String>,
|
|
||||||
value: &T,
|
|
||||||
remote_messages: &mut Vec<cultnet_rs::CultNetMessage>,
|
|
||||||
) -> Result<()>
|
|
||||||
where
|
|
||||||
T: DatabaseEntry + serde::Serialize,
|
|
||||||
{
|
|
||||||
let key = key.into();
|
|
||||||
node.put(&key, value)?;
|
|
||||||
if let Some(remote) = &self.remote {
|
|
||||||
remote_messages.push(node.create_rudp_document_message(
|
|
||||||
&key,
|
|
||||||
value,
|
|
||||||
&remote.options(),
|
|
||||||
)?);
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn provider_advertisement(identity: &MeshRuntimeIdentity, updated_at: &str) -> Value {
|
|
||||||
json!({
|
|
||||||
"schema":"gamecult.eve.provider_advertisement.v1",
|
|
||||||
"providerId":PROVIDER_ID,
|
|
||||||
"serviceId":identity.service_id,
|
|
||||||
"verseId":"gamecult.private",
|
|
||||||
"rootVerse":"gamecult",
|
|
||||||
"canonicalService":"ghostlight-dungeon",
|
|
||||||
"locatedService":identity.located_service,
|
|
||||||
"cultMeshAddress":"cultmesh://gamecult.private/ghostlight/providers/dungeon",
|
|
||||||
"title":"Ghostlight Dungeon",
|
|
||||||
"kind":"narrative.simulation",
|
|
||||||
"updatedAtUtc":updated_at,
|
|
||||||
"freshness":{"state":"live","lastSeenAtUtc":updated_at,"maxAgeMs":360000},
|
|
||||||
"schemas":[
|
|
||||||
"gamecult.eve.surface.v1",
|
|
||||||
"gamecult.eve.command_invocation.v1",
|
|
||||||
COMMAND_RESULT_SCHEMA,
|
|
||||||
"heimdall.access_gate_state.v1",
|
|
||||||
STATE_SCHEMA,
|
|
||||||
CONSUMER_PATCH_SCHEMA,
|
|
||||||
CONSUMER_RECEIPT_SCHEMA
|
|
||||||
],
|
|
||||||
"witnesses":[{
|
|
||||||
"kind":"source-commit",
|
|
||||||
"ref":option_env!("GHOSTLIGHT_BUILD_COMMIT").unwrap_or("development")
|
|
||||||
}],
|
|
||||||
"surfaces":[{
|
|
||||||
"surfaceId":SURFACE_ID,
|
|
||||||
"schema":"gamecult.eve.surface.v1",
|
|
||||||
"url":"/api/eve/surfaces/ghostlight.play",
|
|
||||||
"transport":"https-json",
|
|
||||||
"status":"available",
|
|
||||||
"surfaceKind":"subject-scoped-narrative",
|
|
||||||
"interactionModel":"typed-command-receipts",
|
|
||||||
"worldInteraction":{
|
|
||||||
"projectionKind":"owner-derived",
|
|
||||||
"stateSchemas":[STATE_SCHEMA],
|
|
||||||
"commandBoundary":COMMAND_BOUNDARY,
|
|
||||||
"receiptSchema":COMMAND_RESULT_SCHEMA,
|
|
||||||
"loweringTargets":["browser","eve-native","tui"],
|
|
||||||
"ownership":"One Ghostlight WorldMailbox owns state; Eve lowers derived projections and commands."
|
|
||||||
},
|
|
||||||
"requiresPlugins":[{
|
|
||||||
"pluginId":"gamecult.heimdall.access",
|
|
||||||
"versionRange":"^1.0.0",
|
|
||||||
"availability":"required",
|
|
||||||
"requiredCapabilities":["auth.gate","auth.begin","auth.complete","auth.logout"]
|
|
||||||
}]
|
|
||||||
}],
|
|
||||||
"commands":[{
|
|
||||||
"command":COMMAND_BOUNDARY,
|
|
||||||
"transport":"https-json",
|
|
||||||
"summary":"Canonical Ghostlight Eve command boundary."
|
|
||||||
}]
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
impl RemoteReplication {
|
|
||||||
fn start(target: SocketAddr, runtime_id: String) -> Result<Self> {
|
|
||||||
let pending = Arc::new((
|
|
||||||
Mutex::new(None::<Vec<cultnet_rs::CultNetMessage>>),
|
|
||||||
Condvar::new(),
|
|
||||||
));
|
|
||||||
let worker_pending = pending.clone();
|
|
||||||
let worker_runtime_id = runtime_id.clone();
|
|
||||||
let alive = Arc::new(AtomicBool::new(true));
|
|
||||||
let worker_alive = alive.clone();
|
|
||||||
thread::Builder::new()
|
|
||||||
.name("ghostlight-odin-rudp".into())
|
|
||||||
.spawn(move || {
|
|
||||||
struct Liveness(Arc<AtomicBool>);
|
|
||||||
impl Drop for Liveness {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
self.0.store(false, Ordering::Release);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let _liveness = Liveness(worker_alive);
|
|
||||||
loop {
|
|
||||||
let messages = {
|
|
||||||
let (lock, ready) = &*worker_pending;
|
|
||||||
let mut pending = lock
|
|
||||||
.lock()
|
|
||||||
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
|
||||||
while pending.is_none() {
|
|
||||||
pending = ready
|
|
||||||
.wait(pending)
|
|
||||||
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
|
||||||
}
|
|
||||||
pending.take().unwrap_or_default()
|
|
||||||
};
|
|
||||||
if messages.is_empty() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let options = remote_options(target, &worker_runtime_id);
|
|
||||||
if let Err(error) =
|
|
||||||
publish_cultnet_messages_to_rudp_catalog(&messages, options)
|
|
||||||
{
|
|
||||||
tracing::warn!(
|
|
||||||
document_count = messages.len(),
|
|
||||||
%target,
|
|
||||||
%error,
|
|
||||||
"Odin publication failed; retaining the newest derived projection for retry"
|
|
||||||
);
|
|
||||||
let (lock, ready) = &*worker_pending;
|
|
||||||
let mut pending = lock
|
|
||||||
.lock()
|
|
||||||
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
|
||||||
if pending.is_none() {
|
|
||||||
*pending = Some(messages);
|
|
||||||
}
|
|
||||||
let _ = ready
|
|
||||||
.wait_timeout(pending, std::time::Duration::from_secs(2))
|
|
||||||
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})?;
|
|
||||||
Ok(Self {
|
|
||||||
target,
|
|
||||||
runtime_id,
|
|
||||||
pending,
|
|
||||||
alive,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_alive(&self) -> bool {
|
|
||||||
self.alive.load(Ordering::Acquire)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn options(&self) -> CultMeshRudpDocumentPublishOptions {
|
|
||||||
remote_options(self.target, &self.runtime_id)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn enqueue(&self, messages: Vec<cultnet_rs::CultNetMessage>) {
|
|
||||||
let (lock, ready) = &*self.pending;
|
|
||||||
let mut pending = lock.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
|
||||||
*pending = Some(messages);
|
|
||||||
ready.notify_one();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn remote_options(target: SocketAddr, runtime_id: &str) -> CultMeshRudpDocumentPublishOptions {
|
|
||||||
let mut options = CultMeshRudpDocumentPublishOptions::odin(target, runtime_id);
|
|
||||||
options.source_agent_id = Some(PROVIDER_ID.into());
|
|
||||||
options.source_role = Some("narrative-simulation".into());
|
|
||||||
options.tags = vec!["ghostlight".into(), "eve".into(), "private".into()];
|
|
||||||
options
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn publishes_only_owner_derived_surface_and_health() {
|
|
||||||
let directory = tempfile::tempdir().unwrap();
|
|
||||||
let publisher = MeshPublisher::open(
|
|
||||||
directory.path().join("mesh-v2.cc"),
|
|
||||||
None,
|
|
||||||
MeshRuntimeIdentity::default(),
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
let health = publisher.publish(None).unwrap();
|
|
||||||
assert_eq!(health["worldState"], "empty");
|
|
||||||
assert_eq!(health["surfaceVersion"], 0);
|
|
||||||
assert_eq!(publisher.health().unwrap(), health);
|
|
||||||
let node = publisher.node.lock().unwrap();
|
|
||||||
let surface = node
|
|
||||||
.get_required::<EveSurfaceRecord>(SURFACE_KEY)
|
|
||||||
.unwrap()
|
|
||||||
.value;
|
|
||||||
assert_eq!(surface["type"], "surface-state");
|
|
||||||
assert_eq!(surface["schema"], "gamecult.eve.surface.v1");
|
|
||||||
assert_eq!(surface["providerId"], PROVIDER_ID);
|
|
||||||
assert_eq!(surface["version"], 0);
|
|
||||||
assert!(
|
|
||||||
surface["updatedAtUtc"]
|
|
||||||
.as_str()
|
|
||||||
.is_some_and(|value| value.parse::<DateTime<Utc>>().is_ok())
|
|
||||||
);
|
|
||||||
assert_eq!(surface["surface"], eve::mesh_surface(None)["surface"]);
|
|
||||||
assert_eq!(surface["commands"], eve::mesh_surface(None)["commands"]);
|
|
||||||
assert!(
|
|
||||||
node.get_required::<EveProviderAdvertisementRecord>(ADVERTISEMENT_KEY)
|
|
||||||
.is_ok()
|
|
||||||
);
|
|
||||||
assert!(node.get_required::<ServiceHealthRecord>(HEALTH_KEY).is_ok());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn unavailable_odin_cannot_block_local_publication() {
|
|
||||||
let directory = tempfile::tempdir().unwrap();
|
|
||||||
let publisher = MeshPublisher::open(
|
|
||||||
directory.path().join("mesh-v2.cc"),
|
|
||||||
Some("127.0.0.1:1".parse().unwrap()),
|
|
||||||
MeshRuntimeIdentity::default(),
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
let started = std::time::Instant::now();
|
|
||||||
publisher.publish(None).unwrap();
|
|
||||||
assert!(started.elapsed() < std::time::Duration::from_millis(500));
|
|
||||||
assert_eq!(publisher.health().unwrap()["worldState"], "empty");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn stopped_odin_worker_makes_runtime_health_non_green() {
|
|
||||||
let directory = tempfile::tempdir().unwrap();
|
|
||||||
let publisher = MeshPublisher::open(
|
|
||||||
directory.path().join("mesh-v2.cc"),
|
|
||||||
Some("127.0.0.1:1".parse().unwrap()),
|
|
||||||
MeshRuntimeIdentity::default(),
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
publisher.publish(None).unwrap();
|
|
||||||
publisher
|
|
||||||
.remote
|
|
||||||
.as_ref()
|
|
||||||
.unwrap()
|
|
||||||
.alive
|
|
||||||
.store(false, Ordering::Release);
|
|
||||||
assert!(publisher.health().is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn advertisement_has_one_surface_and_one_command_boundary() {
|
|
||||||
let directory = tempfile::tempdir().unwrap();
|
|
||||||
let publisher = MeshPublisher::open(
|
|
||||||
directory.path().join("mesh-v2.cc"),
|
|
||||||
None,
|
|
||||||
MeshRuntimeIdentity::default(),
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
let advertisement = publisher.provider_advertisement("2026-09-01T00:00:00Z");
|
|
||||||
assert_eq!(advertisement["surfaces"].as_array().unwrap().len(), 1);
|
|
||||||
assert_eq!(advertisement["commands"].as_array().unwrap().len(), 1);
|
|
||||||
assert_eq!(advertisement["surfaces"][0]["surfaceId"], SURFACE_ID);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
44
crates/ghostlight-dungeon/src/page.rs
Normal file
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) }))
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load diff
1394
crates/ghostlight-dungeon/src/playtest.rs
Normal file
1394
crates/ghostlight-dungeon/src/playtest.rs
Normal file
File diff suppressed because it is too large
Load diff
1442
crates/ghostlight-dungeon/src/playtest_atlas.rs
Normal file
1442
crates/ghostlight-dungeon/src/playtest_atlas.rs
Normal file
File diff suppressed because it is too large
Load diff
196
crates/ghostlight-dungeon/src/run_ahead.rs
Normal file
196
crates/ghostlight-dungeon/src/run_ahead.rs
Normal file
|
|
@ -0,0 +1,196 @@
|
||||||
|
//! Run-ahead: the bounded Active elaboration sweep.
|
||||||
|
//!
|
||||||
|
//! A world's scale deficit is answered after play starts, not before: one sweep
|
||||||
|
//! once Begin activates a seeded world, and one after each closed turn. Each
|
||||||
|
//! sweep claims what attention holds first (`focus_of`: the player's place and
|
||||||
|
//! the DM's standing focus), holds at most `Scale::sweep_permits` permits, and
|
||||||
|
//! spends in its own post-turn window: the elaborator calls a provider only
|
||||||
|
//! through the window's recording port, which refuses a call that could pass the
|
||||||
|
//! timeline's elaboration allowance, so how much a sweep does is the DM's knob
|
||||||
|
//! and not a session count. The elaborator reads the evidence of the snapshot
|
||||||
|
//! its timeline is bound to, the same evidence the seed read; an unseeded world
|
||||||
|
//! reads none.
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
begin::{Scale, Vaults},
|
||||||
|
catalog::Catalog,
|
||||||
|
knobs::{DmKnobs, Target},
|
||||||
|
timelines::TimelineHost,
|
||||||
|
};
|
||||||
|
use ghostlight::{
|
||||||
|
ControllerMode, EntityId, EvidenceSource, Focus, Hierarchy, NullEvidenceSource, WorldSnapshot,
|
||||||
|
};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use tokio::sync::{Mutex, Semaphore};
|
||||||
|
|
||||||
|
/// One bounded sweep of `host` over `evidence`. A sweep already running on this
|
||||||
|
/// timeline is the trigger's answer: the sweep that follows picks up what this
|
||||||
|
/// one would have.
|
||||||
|
pub(crate) async fn run_ahead(host: &TimelineHost, evidence: Arc<dyn EvidenceSource>, scale: &Scale) {
|
||||||
|
let Ok(_running) = host.sweeping.try_lock() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let world = match host.world.snapshot().await {
|
||||||
|
Ok(world) => world,
|
||||||
|
Err(error) => {
|
||||||
|
tracing::warn!(%error, "run-ahead could not read the world");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let hierarchy = match host.world.hierarchy().await {
|
||||||
|
Ok(hierarchy) => hierarchy,
|
||||||
|
Err(error) => {
|
||||||
|
tracing::warn!(%error, "run-ahead could not read the hierarchy");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let knobs = host.knobs.lock().await.current();
|
||||||
|
let window = match host.window(world.revision, &world, knobs.allowances) {
|
||||||
|
Ok(window) => Arc::new(window),
|
||||||
|
Err(error) => {
|
||||||
|
tracing::warn!(%error, "run-ahead could not open its window");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let runner = host.controllers.elaborator(window, evidence);
|
||||||
|
let permits = Arc::new(Semaphore::new(scale.sweep_permits));
|
||||||
|
if let Err(error) = runner.sweep(permits, usize::MAX, &focus_of(&world, &hierarchy, &knobs)).await {
|
||||||
|
tracing::warn!(%error, "run-ahead elaboration stopped");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The places the world's owner's own human subjects stand in: the room the
|
||||||
|
/// player is in, which the DM's `react` owns and a world wave never turns.
|
||||||
|
pub(crate) fn player_places(world: &WorldSnapshot) -> Vec<EntityId> {
|
||||||
|
world
|
||||||
|
.subjects
|
||||||
|
.iter()
|
||||||
|
.filter(|subject| {
|
||||||
|
subject.controller_mode == Some(ControllerMode::Human)
|
||||||
|
&& subject.human_controller.as_ref() == Some(&world.owner)
|
||||||
|
})
|
||||||
|
.filter_map(|subject| world.place_of(subject.id))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where attention is: the player's place, then the DM's focus entries whose
|
||||||
|
/// lease still holds. A world with no placed player and no entries has no
|
||||||
|
/// focus, and its sweep keeps the kernel's order.
|
||||||
|
pub(crate) fn focus_of(world: &WorldSnapshot, hierarchy: &Hierarchy, knobs: &DmKnobs) -> Focus {
|
||||||
|
let mut focus = Focus { places: player_places(world), nodes: Vec::new() };
|
||||||
|
for lease in knobs.standing(world.now.0) {
|
||||||
|
match lease.target {
|
||||||
|
Target::Place(place) if !focus.places.contains(&place) => focus.places.push(place),
|
||||||
|
Target::Place(_) => {}
|
||||||
|
Target::Institution(_) => focus.nodes.extend(lease.target.node(hierarchy)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
focus
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The evidence a timeline's elaborator reads: its bound snapshot's, for the
|
||||||
|
/// era its world was pinned to, or none for a world that began unseeded. A
|
||||||
|
/// bound snapshot that cannot be reopened, or a world that cannot be read,
|
||||||
|
/// yields no evidence at all and no sweep, never a blind or era-blind one.
|
||||||
|
pub(crate) async fn evidence_of(
|
||||||
|
catalog: &Mutex<Catalog>,
|
||||||
|
vaults: &dyn Vaults,
|
||||||
|
host: &TimelineHost,
|
||||||
|
timeline: &str,
|
||||||
|
) -> Option<Arc<dyn EvidenceSource>> {
|
||||||
|
let snapshot_id = {
|
||||||
|
let catalog = catalog.lock().await;
|
||||||
|
let world = catalog.world(&catalog.timeline(timeline)?.world_id)?;
|
||||||
|
world.snapshot_id.clone()
|
||||||
|
};
|
||||||
|
let Some(id) = snapshot_id else {
|
||||||
|
return Some(Arc::new(NullEvidenceSource));
|
||||||
|
};
|
||||||
|
let era = host.world.snapshot().await.ok()?.era;
|
||||||
|
match vaults.evidence(&id, era.as_ref().map(|era| era.id.as_str())) {
|
||||||
|
Ok(evidence) => Some(evidence),
|
||||||
|
Err(error) => {
|
||||||
|
tracing::warn!(%error, timeline, "a seeded timeline's snapshot could not be reopened");
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::{
|
||||||
|
begin::{
|
||||||
|
BeginRequest, begin,
|
||||||
|
tests::{NoVaults, deferred_rig, one_vault, principal, request},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
/// The sweep looks where the player stands: the place of the owner's own
|
||||||
|
/// human subject, and nowhere for a world whose owner controls no subject.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn the_focus_of_a_world_is_its_owners_human_subjects_place() {
|
||||||
|
let rig = deferred_rig();
|
||||||
|
let begun = begin(&rig.catalog, &rig.timelines, &NoVaults, &rig.scale, &principal("alice"), request(Uuid::new_v4(), None))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let host = rig.timelines.host(&begun.timeline).await.unwrap();
|
||||||
|
let world = host.world.snapshot().await.unwrap();
|
||||||
|
let player = world
|
||||||
|
.subjects
|
||||||
|
.iter()
|
||||||
|
.find(|subject| subject.human_controller.as_ref() == Some(&world.owner))
|
||||||
|
.expect("the owner's player");
|
||||||
|
let stands = world.place_of(player.id).expect("the player stands somewhere");
|
||||||
|
let hierarchy = host.world.hierarchy().await.unwrap();
|
||||||
|
let none = DmKnobs::default();
|
||||||
|
assert_eq!(focus_of(&world, &hierarchy, &none).places, vec![stands]);
|
||||||
|
|
||||||
|
let mut stranger = world.clone();
|
||||||
|
stranger.owner = ghostlight::PrincipalId::new("someone else");
|
||||||
|
assert!(focus_of(&stranger, &hierarchy, &none).places.is_empty(), "another principal's subject is not the owner's player");
|
||||||
|
let mut automaton = world;
|
||||||
|
for subject in &mut automaton.subjects {
|
||||||
|
subject.controller_mode = Some(ControllerMode::NarrativePersona);
|
||||||
|
}
|
||||||
|
assert!(focus_of(&automaton, &hierarchy, &none).places.is_empty(), "a persona is not looking");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A timeline's elaborator reads what its world was bound to: nothing
|
||||||
|
/// for an unseeded world, the snapshot for a seeded one, and no evidence
|
||||||
|
/// (so no sweep) for a snapshot that cannot be reopened or a timeline the
|
||||||
|
/// catalog does not know.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn the_evidence_of_a_timeline_is_its_bound_snapshots() {
|
||||||
|
let vaults = one_vault();
|
||||||
|
let rig = deferred_rig();
|
||||||
|
let alice = principal("alice");
|
||||||
|
let unseeded = begin(&rig.catalog, &rig.timelines, &NoVaults, &rig.scale, &alice, request(Uuid::new_v4(), None))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let host = rig.timelines.host(&unseeded.timeline).await.unwrap();
|
||||||
|
assert!(
|
||||||
|
evidence_of(&rig.catalog, &NoVaults, &host, &unseeded.timeline).await.is_some(),
|
||||||
|
"an unseeded world reads none, and still sweeps"
|
||||||
|
);
|
||||||
|
let seeded = begin(
|
||||||
|
&rig.catalog,
|
||||||
|
&rig.timelines,
|
||||||
|
vaults.as_ref(),
|
||||||
|
&rig.scale,
|
||||||
|
&alice,
|
||||||
|
BeginRequest { era: Some("b".into()), ..request(Uuid::new_v4(), Some("delvehold")) },
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let host = rig.timelines.host(&seeded.timeline).await.unwrap();
|
||||||
|
assert!(evidence_of(&rig.catalog, vaults.as_ref(), &host, &seeded.timeline).await.is_some());
|
||||||
|
assert!(
|
||||||
|
evidence_of(&rig.catalog, &NoVaults, &host, &seeded.timeline).await.is_none(),
|
||||||
|
"an unreadable snapshot is never swept blind"
|
||||||
|
);
|
||||||
|
let stranger = "timeline:00000000-0000-4000-8000-000000000000";
|
||||||
|
assert!(evidence_of(&rig.catalog, vaults.as_ref(), &host, stranger).await.is_none());
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load diff
619
crates/ghostlight-dungeon/src/session_refresh.rs
Normal file
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}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
211
crates/ghostlight-dungeon/src/state_layout.rs
Normal file
211
crates/ghostlight-dungeon/src/state_layout.rs
Normal file
|
|
@ -0,0 +1,211 @@
|
||||||
|
//! The admitted state layout: every declared state path must be a direct,
|
||||||
|
//! single-linked regular file or directory before anything is written to it.
|
||||||
|
|
||||||
|
use anyhow::{Context, bail, ensure};
|
||||||
|
use std::{
|
||||||
|
fs,
|
||||||
|
path::{Path, PathBuf},
|
||||||
|
};
|
||||||
|
|
||||||
|
/// The stores one timeline owns, each proved direct before it is opened.
|
||||||
|
pub(crate) const TIMELINE_STORES: [&str; 6] = [
|
||||||
|
"world.cc",
|
||||||
|
"controller-work.cc",
|
||||||
|
"play-turn-v1.cc",
|
||||||
|
"calls.cc",
|
||||||
|
"waves.cc",
|
||||||
|
"gestalt-knobs.cc",
|
||||||
|
];
|
||||||
|
|
||||||
|
fn default_runtime_root() -> PathBuf {
|
||||||
|
#[cfg(windows)]
|
||||||
|
{
|
||||||
|
PathBuf::from(r"F:\GameCult\GhostlightDungeon")
|
||||||
|
}
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
{
|
||||||
|
PathBuf::from("/var/lib/gamecult/ghostlight-dungeon")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn admitted_runtime_root(binding: Option<PathBuf>) -> anyhow::Result<PathBuf> {
|
||||||
|
let Some(binding) = binding else {
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
bail!("--state-root is mandatory for the managed Linux runtime");
|
||||||
|
#[cfg(not(target_os = "linux"))]
|
||||||
|
return Ok(default_runtime_root());
|
||||||
|
};
|
||||||
|
ensure!(binding.is_absolute(), "state-root binding is not absolute");
|
||||||
|
let metadata = fs::symlink_metadata(&binding)
|
||||||
|
.with_context(|| format!("inspecting state-root binding {}", binding.display()))?;
|
||||||
|
ensure!(
|
||||||
|
metadata.is_dir() && !metadata.file_type().is_symlink(),
|
||||||
|
"state-root binding is not a direct directory"
|
||||||
|
);
|
||||||
|
let canonical = fs::canonicalize(&binding)
|
||||||
|
.with_context(|| format!("canonicalizing state-root binding {}", binding.display()))?;
|
||||||
|
ensure!(
|
||||||
|
canonical == binding,
|
||||||
|
"state-root binding is indirect or non-canonical"
|
||||||
|
);
|
||||||
|
Ok(binding)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ensure_direct_directory(path: &Path, label: &str) -> anyhow::Result<()> {
|
||||||
|
match fs::symlink_metadata(path) {
|
||||||
|
Ok(_) => {}
|
||||||
|
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||||
|
fs::create_dir(path)
|
||||||
|
.with_context(|| format!("creating direct {label} {}", path.display()))?;
|
||||||
|
}
|
||||||
|
Err(error) => return Err(error).with_context(|| format!("inspecting {label}")),
|
||||||
|
}
|
||||||
|
let metadata = fs::symlink_metadata(path)
|
||||||
|
.with_context(|| format!("inspecting {label} {}", path.display()))?;
|
||||||
|
ensure!(
|
||||||
|
metadata.is_dir() && !metadata.file_type().is_symlink(),
|
||||||
|
"{label} is indirect or not a directory"
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn prepare_admitted_state_layout(runtime_root: &Path) -> anyhow::Result<()> {
|
||||||
|
let rebound = admitted_runtime_root(Some(runtime_root.to_owned()))?;
|
||||||
|
ensure!(
|
||||||
|
rebound == runtime_root,
|
||||||
|
"state-root binding changed after process-write-lease admission"
|
||||||
|
);
|
||||||
|
let service_root = runtime_root.join("service");
|
||||||
|
ensure_direct_directory(&service_root, "service state directory")?;
|
||||||
|
ensure_direct_directory(&runtime_root.join("timelines"), "timelines directory")?;
|
||||||
|
ensure_direct_directory(
|
||||||
|
&runtime_root.join(crate::vaults::SNAPSHOT_DIRECTORY),
|
||||||
|
"vault snapshot directory",
|
||||||
|
)?;
|
||||||
|
for path in [
|
||||||
|
runtime_root.join("catalog.cc"),
|
||||||
|
service_root.join("app-sessions-v2.cc"),
|
||||||
|
] {
|
||||||
|
require_direct_state_file_or_absent(&path)?;
|
||||||
|
require_direct_state_file_or_absent(&sibling_state_lock_path(&path))?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Proves a timeline's stores direct before it is opened and returns its
|
||||||
|
/// directory, created if absent.
|
||||||
|
pub(crate) fn prepare_timeline_directory(
|
||||||
|
runtime_root: &Path,
|
||||||
|
directory_name: &str,
|
||||||
|
) -> anyhow::Result<PathBuf> {
|
||||||
|
let directory = runtime_root.join("timelines").join(directory_name);
|
||||||
|
ensure_direct_directory(&directory, "timeline directory")?;
|
||||||
|
for name in TIMELINE_STORES {
|
||||||
|
let path = directory.join(name);
|
||||||
|
require_direct_state_file_or_absent(&path)?;
|
||||||
|
require_direct_state_file_or_absent(&sibling_state_lock_path(&path))?;
|
||||||
|
}
|
||||||
|
Ok(directory)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn require_direct_state_file_or_absent(path: &Path) -> anyhow::Result<()> {
|
||||||
|
match fs::symlink_metadata(path) {
|
||||||
|
Ok(metadata) => {
|
||||||
|
ensure!(
|
||||||
|
metadata.is_file() && !metadata.file_type().is_symlink(),
|
||||||
|
"declared state path {} is indirect or not a regular file",
|
||||||
|
path.display()
|
||||||
|
);
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
ensure!(
|
||||||
|
std::os::unix::fs::MetadataExt::nlink(&metadata) == 1,
|
||||||
|
"declared state path {} is multiply linked",
|
||||||
|
path.display()
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
||||||
|
Err(error) => {
|
||||||
|
Err(error).with_context(|| format!("inspecting declared state path {}", path.display()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sibling_state_lock_path(path: &Path) -> PathBuf {
|
||||||
|
let mut name = path
|
||||||
|
.file_name()
|
||||||
|
.map(|value| value.to_os_string())
|
||||||
|
.unwrap_or_else(|| "state.cc".into());
|
||||||
|
name.push(".lock");
|
||||||
|
path.with_file_name(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
#[test]
|
||||||
|
fn managed_linux_runtime_requires_the_admitted_state_root_binding() {
|
||||||
|
assert!(admitted_runtime_root(None).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn admitted_state_root_must_name_the_direct_canonical_directory() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let root = fs::canonicalize(directory.path()).unwrap();
|
||||||
|
assert_eq!(admitted_runtime_root(Some(root.clone())).unwrap(), root);
|
||||||
|
assert!(admitted_runtime_root(Some(directory.path().join("missing"))).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn post_lease_state_layout_creates_only_the_direct_declared_directories() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let root = fs::canonicalize(directory.path()).unwrap();
|
||||||
|
prepare_admitted_state_layout(&root).unwrap();
|
||||||
|
for name in ["service", "timelines"] {
|
||||||
|
let metadata = fs::symlink_metadata(root.join(name)).unwrap();
|
||||||
|
assert!(metadata.is_dir());
|
||||||
|
assert!(!metadata.file_type().is_symlink());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
#[test]
|
||||||
|
fn post_lease_state_layout_rejects_symlinks_and_hardlinks() {
|
||||||
|
use std::os::unix::fs::symlink;
|
||||||
|
|
||||||
|
let symlink_directory = tempfile::tempdir().unwrap();
|
||||||
|
let symlink_root = fs::canonicalize(symlink_directory.path()).unwrap();
|
||||||
|
let target = symlink_root.join("other.cc");
|
||||||
|
fs::write(&target, b"not-catalog").unwrap();
|
||||||
|
symlink(&target, symlink_root.join("catalog.cc")).unwrap();
|
||||||
|
assert!(prepare_admitted_state_layout(&symlink_root).is_err());
|
||||||
|
|
||||||
|
let hardlink_directory = tempfile::tempdir().unwrap();
|
||||||
|
let hardlink_root = fs::canonicalize(hardlink_directory.path()).unwrap();
|
||||||
|
let target = hardlink_root.join("other.cc");
|
||||||
|
fs::write(&target, b"not-catalog").unwrap();
|
||||||
|
fs::hard_link(&target, hardlink_root.join("catalog.cc")).unwrap();
|
||||||
|
assert!(prepare_admitted_state_layout(&hardlink_root).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A timeline's own stores get the same proof as the service's, before the
|
||||||
|
/// timeline is opened: a symlink standing in for its play-turn store is
|
||||||
|
/// refused.
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
#[test]
|
||||||
|
fn a_symlinked_timeline_store_is_refused() {
|
||||||
|
use std::os::unix::fs::symlink;
|
||||||
|
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let root = fs::canonicalize(directory.path()).unwrap();
|
||||||
|
prepare_admitted_state_layout(&root).unwrap();
|
||||||
|
let name = "00000000-0000-4000-8000-000000000001";
|
||||||
|
let timeline = prepare_timeline_directory(&root, name).unwrap();
|
||||||
|
let target = root.join("other.cc");
|
||||||
|
fs::write(&target, b"not-play-turn").unwrap();
|
||||||
|
symlink(&target, timeline.join("play-turn-v1.cc")).unwrap();
|
||||||
|
assert!(prepare_timeline_directory(&root, name).is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
177
crates/ghostlight-dungeon/src/test_support.rs
Normal file
177
crates/ghostlight-dungeon/src/test_support.rs
Normal file
|
|
@ -0,0 +1,177 @@
|
||||||
|
//! Test support the API tests, the live runtime check and the playtest
|
||||||
|
//! harness share: a counting port that keeps usage per model, and the one
|
||||||
|
//! assembly of an `AppState` with signed-in test sessions.
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
app_session::AppSessionOwner,
|
||||||
|
begin::{Scale, Vaults},
|
||||||
|
catalog::Catalog,
|
||||||
|
heimdall::{HeimdallPort, VerifiedSessionAdmission},
|
||||||
|
runtime::AppState,
|
||||||
|
timelines::Timelines,
|
||||||
|
};
|
||||||
|
/// The one neutral model id every test lane runs on: ids are opaque exact
|
||||||
|
/// strings, so no fixture names a provider or tier.
|
||||||
|
pub(crate) const TEST_LANE_MODEL: &str = "test/lane-a";
|
||||||
|
|
||||||
|
use chrono::Utc;
|
||||||
|
use ghostlight::{
|
||||||
|
InferenceFault, InferenceOutput, InferencePort, InferenceRequest, PreparedInference,
|
||||||
|
};
|
||||||
|
use serde_json::Value;
|
||||||
|
use std::{
|
||||||
|
collections::BTreeMap,
|
||||||
|
path::Path,
|
||||||
|
sync::{Arc, Mutex as StdMutex},
|
||||||
|
};
|
||||||
|
use tokio::sync::{Mutex, mpsc};
|
||||||
|
|
||||||
|
/// What one model was asked and what the provider says it spent.
|
||||||
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||||
|
pub(crate) struct ModelUsage {
|
||||||
|
pub(crate) calls: u64,
|
||||||
|
pub(crate) prompt: u64,
|
||||||
|
pub(crate) cached_prompt: u64,
|
||||||
|
pub(crate) completion: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Counts every call and the usage the connector reports, per model, around
|
||||||
|
/// the real port.
|
||||||
|
pub(crate) struct CountingPort {
|
||||||
|
inner: Arc<dyn InferencePort>,
|
||||||
|
usage: StdMutex<BTreeMap<String, ModelUsage>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CountingPort {
|
||||||
|
pub(crate) fn new(inner: Arc<dyn InferencePort>) -> Arc<Self> {
|
||||||
|
Arc::new(Self { inner, usage: StdMutex::new(BTreeMap::new()) })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn by_model(&self) -> BTreeMap<String, ModelUsage> {
|
||||||
|
self.usage.lock().unwrap().clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn totals(&self) -> ModelUsage {
|
||||||
|
self.by_model().values().fold(ModelUsage::default(), |sum, each| ModelUsage {
|
||||||
|
calls: sum.calls + each.calls,
|
||||||
|
prompt: sum.prompt + each.prompt,
|
||||||
|
cached_prompt: sum.cached_prompt + each.cached_prompt,
|
||||||
|
completion: sum.completion + each.completion,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The model a prepared request names: the `model` key wherever the request's
|
||||||
|
/// serialization keeps it, including inside a string that holds JSON.
|
||||||
|
fn model_of(value: &Value) -> Option<String> {
|
||||||
|
match value {
|
||||||
|
Value::Object(map) => map
|
||||||
|
.get("model")
|
||||||
|
.and_then(Value::as_str)
|
||||||
|
.map(str::to_owned)
|
||||||
|
.or_else(|| map.values().find_map(model_of)),
|
||||||
|
Value::Array(items) => items.iter().find_map(model_of),
|
||||||
|
Value::String(text) if text.starts_with('{') => {
|
||||||
|
serde_json::from_str::<Value>(text).ok().and_then(|inner| model_of(&inner))
|
||||||
|
}
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl InferencePort for CountingPort {
|
||||||
|
fn prepare(&self, request: InferenceRequest) -> Result<PreparedInference, InferenceFault> {
|
||||||
|
self.inner.prepare(request)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn infer(&self, request: PreparedInference) -> Result<InferenceOutput, InferenceFault> {
|
||||||
|
let model = serde_json::to_value(&request)
|
||||||
|
.ok()
|
||||||
|
.and_then(|seen| model_of(&seen))
|
||||||
|
.unwrap_or_else(|| "unknown".into());
|
||||||
|
let output = self.inner.infer(request).await?;
|
||||||
|
let usage = output.usage();
|
||||||
|
let mut table = self.usage.lock().unwrap();
|
||||||
|
let row = table.entry(model).or_default();
|
||||||
|
row.calls += 1;
|
||||||
|
if let Some(usage) = usage {
|
||||||
|
row.prompt += usage.prompt;
|
||||||
|
row.cached_prompt += usage.cached_prompt.unwrap_or(0);
|
||||||
|
row.completion += usage.completion;
|
||||||
|
}
|
||||||
|
Ok(output)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An `AppState` over the given pieces with one signed-in session per entry of
|
||||||
|
/// `accounts` (the same account twice is the same player on two devices), the
|
||||||
|
/// session cookies in order, and the receiver of the fatal signals. Session
|
||||||
|
/// custody lives under `directory`.
|
||||||
|
pub(crate) fn assemble(
|
||||||
|
directory: &Path,
|
||||||
|
catalog: Arc<Mutex<Catalog>>,
|
||||||
|
timelines: Arc<Timelines>,
|
||||||
|
scale: Arc<Scale>,
|
||||||
|
vaults: Arc<dyn Vaults>,
|
||||||
|
heimdall: Arc<dyn HeimdallPort>,
|
||||||
|
accounts: &[&str],
|
||||||
|
) -> (AppState, Vec<String>, mpsc::UnboundedReceiver<String>) {
|
||||||
|
let key = directory.join("session.key");
|
||||||
|
std::fs::write(&key, [17_u8; 32]).unwrap();
|
||||||
|
let mut sessions =
|
||||||
|
AppSessionOwner::open(directory.join("service/app-sessions-v2.cc"), &key).unwrap();
|
||||||
|
let cookies = accounts
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(index, account)| {
|
||||||
|
sessions
|
||||||
|
.create_session(VerifiedSessionAdmission::fixture(
|
||||||
|
*account,
|
||||||
|
format!("heimdall-session-{index}"),
|
||||||
|
1,
|
||||||
|
Utc::now() + chrono::Duration::hours(1),
|
||||||
|
Utc::now() + chrono::Duration::days(1),
|
||||||
|
"fixture-refresh",
|
||||||
|
))
|
||||||
|
.unwrap()
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let (fatal, fatal_events) = mpsc::unbounded_channel();
|
||||||
|
let state = AppState {
|
||||||
|
catalog,
|
||||||
|
timelines,
|
||||||
|
vaults,
|
||||||
|
scale,
|
||||||
|
sessions: Arc::new(Mutex::new(sessions)),
|
||||||
|
heimdall,
|
||||||
|
auth: Arc::default(),
|
||||||
|
runtime_id: "ghostlight-test".into(),
|
||||||
|
runtime_health: None,
|
||||||
|
fatal,
|
||||||
|
};
|
||||||
|
(state, cookies, fatal_events)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::play::tests::ScriptedPort;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_prepared_request_names_its_model() {
|
||||||
|
let port = ScriptedPort::new(vec![]);
|
||||||
|
let request = InferenceRequest::play(
|
||||||
|
ghostlight::CommandId::new(),
|
||||||
|
0,
|
||||||
|
TEST_LANE_MODEL,
|
||||||
|
"be brief",
|
||||||
|
vec![],
|
||||||
|
vec![],
|
||||||
|
100,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let prepared = port.prepare(request).unwrap();
|
||||||
|
let seen = serde_json::to_value(&prepared).unwrap();
|
||||||
|
assert_eq!(model_of(&seen).as_deref(), Some(TEST_LANE_MODEL));
|
||||||
|
}
|
||||||
|
}
|
||||||
175
crates/ghostlight-dungeon/src/timelines.rs
Normal file
175
crates/ghostlight-dungeon/src/timelines.rs
Normal file
|
|
@ -0,0 +1,175 @@
|
||||||
|
//! Many timelines in one daemon.
|
||||||
|
//!
|
||||||
|
//! Each timeline is its own kernel store with its own mailbox, play table and
|
||||||
|
//! controller work; every one shares the single routed inference port and the
|
||||||
|
//! one concurrency pool. A timeline opens on first use and stays warm.
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
catalog::timeline_directory_name,
|
||||||
|
knobs::{KnobLog, KnobStore},
|
||||||
|
play::PlayTable,
|
||||||
|
state_layout::prepare_timeline_directory,
|
||||||
|
waves::{WaveLog, WaveStore},
|
||||||
|
};
|
||||||
|
use ghostlight::{
|
||||||
|
CallRecordError, CallRecordStore, ControllerModels, ControllerPort, ControllerRunner,
|
||||||
|
InferencePort, LaneTokens, PersonaLane, RecordingInferencePort, RunId, RunStart, WorldMailbox,
|
||||||
|
WorldSnapshot, open_controller_work,
|
||||||
|
};
|
||||||
|
use anyhow::Context;
|
||||||
|
use std::{collections::HashMap, path::PathBuf, sync::Arc};
|
||||||
|
use tokio::sync::{Mutex, Semaphore, broadcast, mpsc};
|
||||||
|
|
||||||
|
/// What every timeline shares: the one inference port all lanes route through,
|
||||||
|
/// the model each lane runs on, and the concurrency pool sized to the
|
||||||
|
/// connector's quota.
|
||||||
|
pub(crate) struct Shared {
|
||||||
|
pub(crate) inference: Arc<dyn InferencePort>,
|
||||||
|
pub(crate) models: ControllerModels,
|
||||||
|
pub(crate) play_model: String,
|
||||||
|
pub(crate) permits: Arc<Semaphore>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One opened timeline.
|
||||||
|
pub(crate) struct TimelineHost {
|
||||||
|
pub(crate) world: WorldMailbox,
|
||||||
|
pub(crate) controllers: ControllerRunner,
|
||||||
|
pub(crate) play: Arc<PlayTable>,
|
||||||
|
/// Pulsed whenever this timeline's turn changes; the stream wakes on it.
|
||||||
|
pub(crate) changes: broadcast::Sender<()>,
|
||||||
|
/// Held while a run-ahead sweep runs: one at a time per timeline.
|
||||||
|
pub(crate) sweeping: Mutex<()>,
|
||||||
|
/// The spend ledgers of this timeline's background windows, one run each.
|
||||||
|
/// The play turn's own calls never reach it.
|
||||||
|
pub(crate) background: Arc<CallRecordStore>,
|
||||||
|
/// The world waves this timeline's closed turns planned, and what the DM
|
||||||
|
/// has been shown of them.
|
||||||
|
pub(crate) waves: WaveLog,
|
||||||
|
/// The DM's standing knobs for this timeline's world beyond the room.
|
||||||
|
pub(crate) knobs: KnobLog,
|
||||||
|
inference: Arc<dyn InferencePort>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TimelineHost {
|
||||||
|
/// The port of the post-turn window that follows world revision
|
||||||
|
/// `revision`: the one port the background lanes call a provider
|
||||||
|
/// through, reserving each call in the window's ledger first. The window's
|
||||||
|
/// cap is its allowances together. A window at the same revision is the same
|
||||||
|
/// ledger, so a trigger that finds nothing changed spends no new allowance,
|
||||||
|
/// and a wave resumed after a restart reopens the ledger it opened in. The
|
||||||
|
/// caller passes the knobs' allowances every time and the ledger follows them,
|
||||||
|
/// keeping its spend: a tune binds the window already open.
|
||||||
|
/// `world` is the world the window is opened over now.
|
||||||
|
pub(crate) fn window(
|
||||||
|
&self,
|
||||||
|
revision: u64,
|
||||||
|
world: &WorldSnapshot,
|
||||||
|
allowances: LaneTokens,
|
||||||
|
) -> Result<RecordingInferencePort, CallRecordError> {
|
||||||
|
let run = RunId::new(&format!("window-{revision}"))?;
|
||||||
|
RecordingInferencePort::open_following(
|
||||||
|
self.inference.clone(),
|
||||||
|
self.background.clone(),
|
||||||
|
run,
|
||||||
|
allowances.total(),
|
||||||
|
allowances,
|
||||||
|
&RunStart::of(world),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct Timelines {
|
||||||
|
root: PathBuf,
|
||||||
|
shared: Shared,
|
||||||
|
hosts: Mutex<HashMap<String, Arc<TimelineHost>>>,
|
||||||
|
fatal: mpsc::UnboundedSender<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Timelines {
|
||||||
|
pub(crate) fn new(root: PathBuf, shared: Shared, fatal: mpsc::UnboundedSender<String>) -> Self {
|
||||||
|
Self {
|
||||||
|
root,
|
||||||
|
shared,
|
||||||
|
hosts: Mutex::new(HashMap::new()),
|
||||||
|
fatal,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn shared(&self) -> &Shared {
|
||||||
|
&self.shared
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The host for `id`, opened on first use. Refuses an id that is not
|
||||||
|
/// exactly `timeline:<canonical uuid>`.
|
||||||
|
pub(crate) async fn host(&self, id: &str) -> anyhow::Result<Arc<TimelineHost>> {
|
||||||
|
let name = timeline_directory_name(id).context("timeline id is not canonical")?;
|
||||||
|
let mut hosts = self.hosts.lock().await;
|
||||||
|
if let Some(host) = hosts.get(id) {
|
||||||
|
return Ok(host.clone());
|
||||||
|
}
|
||||||
|
let directory = prepare_timeline_directory(&self.root, &name)?;
|
||||||
|
let (world, owner) = WorldMailbox::open(directory.join("world.cc"))?;
|
||||||
|
let fatal = self.fatal.clone();
|
||||||
|
let label = id.to_owned();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let _ = owner.await;
|
||||||
|
let _ = fatal.send(format!("world owner of {label} stopped while serving"));
|
||||||
|
});
|
||||||
|
let work = open_controller_work(directory.join("controller-work.cc"))?;
|
||||||
|
let background = Arc::new(
|
||||||
|
CallRecordStore::open(directory.join("calls.cc"))
|
||||||
|
.context("the background call ledger could not be opened")?,
|
||||||
|
);
|
||||||
|
let waves: WaveLog = Arc::new(Mutex::new(
|
||||||
|
WaveStore::open(directory.join("waves.cc")).context("the wave store could not be opened")?,
|
||||||
|
));
|
||||||
|
let knobs: KnobLog = Arc::new(Mutex::new(
|
||||||
|
KnobStore::open(directory.join("gestalt-knobs.cc")).context("the knob store could not be opened")?,
|
||||||
|
));
|
||||||
|
let controllers = ControllerRunner::open(
|
||||||
|
world.clone(),
|
||||||
|
self.shared.inference.clone(),
|
||||||
|
work,
|
||||||
|
self.shared.models.clone(),
|
||||||
|
)?;
|
||||||
|
let personas = PersonaLane::new(
|
||||||
|
ControllerPort::new(world.clone()),
|
||||||
|
self.shared.inference.clone(),
|
||||||
|
self.shared.models.projector.clone(),
|
||||||
|
self.shared.models.persona.clone(),
|
||||||
|
)?;
|
||||||
|
let play = PlayTable::new(
|
||||||
|
world.clone(),
|
||||||
|
personas,
|
||||||
|
self.shared.inference.clone(),
|
||||||
|
self.shared.play_model.clone(),
|
||||||
|
self.shared.permits.clone(),
|
||||||
|
directory.join("play-turn-v1.cc"),
|
||||||
|
)?
|
||||||
|
.with_gears(waves.clone(), knobs.clone());
|
||||||
|
let (changes, _) = broadcast::channel(16);
|
||||||
|
let host = Arc::new(TimelineHost {
|
||||||
|
world,
|
||||||
|
controllers,
|
||||||
|
play: Arc::new(play),
|
||||||
|
changes,
|
||||||
|
sweeping: Mutex::new(()),
|
||||||
|
background,
|
||||||
|
waves,
|
||||||
|
knobs,
|
||||||
|
inference: self.shared.inference.clone(),
|
||||||
|
});
|
||||||
|
hosts.insert(id.to_owned(), host.clone());
|
||||||
|
Ok(host)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every timeline opened so far; readiness probes these.
|
||||||
|
pub(crate) async fn opened(&self) -> Vec<(String, Arc<TimelineHost>)> {
|
||||||
|
self.hosts
|
||||||
|
.lock()
|
||||||
|
.await
|
||||||
|
.iter()
|
||||||
|
.map(|(id, host)| (id.clone(), host.clone()))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
}
|
||||||
249
crates/ghostlight-dungeon/src/turn_log.rs
Normal file
249
crates/ghostlight-dungeon/src/turn_log.rs
Normal file
|
|
@ -0,0 +1,249 @@
|
||||||
|
//! The turn log: what the player was shown, turn by turn, kept for as long as
|
||||||
|
//! the timeline lives.
|
||||||
|
//!
|
||||||
|
//! The kernel journal records what happened in the world, not the prose the
|
||||||
|
//! storyteller wrote about it, and the play row holds only the current turn.
|
||||||
|
//! So the narration a player read exists in one place until the next turn
|
||||||
|
//! replaces it. This log is where it stays. It sits next to the timeline's
|
||||||
|
//! other state and is written by `PlayTable` from the row the screen is drawn
|
||||||
|
//! from, right after that row is committed, so an entry can never say
|
||||||
|
//! something the screen did not. It is append-only: nothing here edits or
|
||||||
|
//! deletes an entry, and a Retry is a new entry that names the one it retries.
|
||||||
|
|
||||||
|
use anyhow::{Context, bail, ensure};
|
||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::{collections::HashMap, path::Path};
|
||||||
|
|
||||||
|
const TYPE: &str = "ghostlight.dungeon_turn_log.v1";
|
||||||
|
|
||||||
|
/// How a submission ended, as the player was told.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub(crate) enum TurnStatus {
|
||||||
|
/// The turn closed and narrated.
|
||||||
|
Committed,
|
||||||
|
/// The world refused an act of the turn; `refusal` holds the line.
|
||||||
|
Refused,
|
||||||
|
/// The turn died on its model; `fault` holds the line shown.
|
||||||
|
Faulted,
|
||||||
|
/// The storyteller asked a question and is waiting; `question` holds it.
|
||||||
|
Asked,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One submission and what it produced. `seq` is its place in the log, from 1.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub(crate) struct LogEntry {
|
||||||
|
pub(crate) seq: u64,
|
||||||
|
pub(crate) turn_id: String,
|
||||||
|
/// Which submission of that turn this is: 1 opens it, each answer adds one.
|
||||||
|
pub(crate) submission: u32,
|
||||||
|
/// The player's text exactly as sent.
|
||||||
|
pub(crate) text: String,
|
||||||
|
pub(crate) narration: Option<String>,
|
||||||
|
pub(crate) question: Option<String>,
|
||||||
|
pub(crate) refusal: Option<String>,
|
||||||
|
pub(crate) fault: Option<String>,
|
||||||
|
pub(crate) status: TurnStatus,
|
||||||
|
/// The world revision the entry rests on, or `None` when the kernel could
|
||||||
|
/// not be read at the moment the entry was written.
|
||||||
|
pub(crate) world_revision: Option<u64>,
|
||||||
|
/// The entry this one retries.
|
||||||
|
pub(crate) retry_of: Option<u64>,
|
||||||
|
pub(crate) recorded_at: DateTime<Utc>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An entry before it has a place in the log.
|
||||||
|
pub(crate) struct NewEntry {
|
||||||
|
pub(crate) turn_id: String,
|
||||||
|
pub(crate) submission: u32,
|
||||||
|
pub(crate) text: String,
|
||||||
|
pub(crate) narration: Option<String>,
|
||||||
|
pub(crate) question: Option<String>,
|
||||||
|
pub(crate) refusal: Option<String>,
|
||||||
|
pub(crate) fault: Option<String>,
|
||||||
|
pub(crate) status: TurnStatus,
|
||||||
|
pub(crate) world_revision: Option<u64>,
|
||||||
|
pub(crate) retry_of: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A page of the log, oldest first, newest last.
|
||||||
|
pub(crate) struct Page {
|
||||||
|
pub(crate) entries: Vec<(LogEntry, Option<u64>)>,
|
||||||
|
/// Pass as `before` to read the page of older entries; `None` at the start.
|
||||||
|
pub(crate) older: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct TurnLog {
|
||||||
|
store: OwnedRedbMessagePackBackingStore,
|
||||||
|
/// Every entry, `entries[n]` having `seq == n + 1`.
|
||||||
|
entries: Vec<LogEntry>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn key_of(seq: u64) -> String {
|
||||||
|
format!("{seq:012}")
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TurnLog {
|
||||||
|
pub(crate) fn open(path: impl AsRef<Path>) -> anyhow::Result<Self> {
|
||||||
|
let store = OwnedRedbMessagePackBackingStore::new(path.as_ref())?;
|
||||||
|
store.validate_path_identity().context("turn log path identity is invalid")?;
|
||||||
|
let mut entries = Vec::new();
|
||||||
|
for row in store.pull_all()? {
|
||||||
|
ensure!(row.r#type == TYPE, "turn log holds a foreign record");
|
||||||
|
let entry: LogEntry = rmp_serde::from_slice(&row.payload).context("a turn log entry did not decode")?;
|
||||||
|
ensure!(row.key == key_of(entry.seq), "a turn log entry sits under the wrong key");
|
||||||
|
entries.push(entry);
|
||||||
|
}
|
||||||
|
entries.sort_by_key(|entry| entry.seq);
|
||||||
|
for (index, entry) in entries.iter().enumerate() {
|
||||||
|
if entry.seq != index as u64 + 1 {
|
||||||
|
bail!("the turn log has a gap before entry {}", entry.seq);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Self { store, entries })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The `seq` of the newest entry; 0 for an empty log.
|
||||||
|
pub(crate) fn last_seq(&self) -> u64 {
|
||||||
|
self.entries.len() as u64
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn contains(&self, seq: u64) -> bool {
|
||||||
|
seq >= 1 && seq <= self.entries.len() as u64
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn recorded(&self, turn_id: &str, submission: u32) -> bool {
|
||||||
|
self.entries
|
||||||
|
.iter()
|
||||||
|
.rev()
|
||||||
|
.any(|entry| entry.turn_id == turn_id && entry.submission == submission)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Appends `new` unless that turn's submission is already recorded.
|
||||||
|
/// Returns the new entry's `seq`, or `None` when it was already there.
|
||||||
|
pub(crate) fn record(&mut self, new: NewEntry) -> anyhow::Result<Option<u64>> {
|
||||||
|
if self.recorded(&new.turn_id, new.submission) {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
if let Some(target) = new.retry_of {
|
||||||
|
ensure!(self.contains(target), "a retry names an entry the log does not hold");
|
||||||
|
}
|
||||||
|
let seq = self.entries.len() as u64 + 1;
|
||||||
|
let entry = LogEntry {
|
||||||
|
seq,
|
||||||
|
turn_id: new.turn_id,
|
||||||
|
submission: new.submission,
|
||||||
|
text: new.text,
|
||||||
|
narration: new.narration,
|
||||||
|
question: new.question,
|
||||||
|
refusal: new.refusal,
|
||||||
|
fault: new.fault,
|
||||||
|
status: new.status,
|
||||||
|
world_revision: new.world_revision,
|
||||||
|
retry_of: new.retry_of,
|
||||||
|
recorded_at: Utc::now(),
|
||||||
|
};
|
||||||
|
let row = CultCacheEnvelope {
|
||||||
|
key: key_of(seq),
|
||||||
|
r#type: TYPE.into(),
|
||||||
|
payload: rmp_serde::to_vec_named(&entry)?,
|
||||||
|
stored_at: entry.recorded_at.to_rfc3339(),
|
||||||
|
schema_id: Some(TYPE.into()),
|
||||||
|
};
|
||||||
|
self.store.validate_path_identity().context("turn log ownership was lost")?;
|
||||||
|
if !self.store.compare_and_swap_batch(&[], vec![row])? {
|
||||||
|
bail!("turn log entry {seq} already exists on disk");
|
||||||
|
}
|
||||||
|
self.entries.push(entry);
|
||||||
|
Ok(Some(seq))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Up to `limit` entries older than `before` (the newest when `None`),
|
||||||
|
/// each with the `seq` of the entry that retried it, if one did.
|
||||||
|
pub(crate) fn page(&self, before: Option<u64>, limit: usize) -> Page {
|
||||||
|
let end = before.map_or(self.entries.len(), |before| (before.saturating_sub(1) as usize).min(self.entries.len()));
|
||||||
|
let start = end.saturating_sub(limit.max(1));
|
||||||
|
let retried_by: HashMap<u64, u64> = self
|
||||||
|
.entries
|
||||||
|
.iter()
|
||||||
|
.rev()
|
||||||
|
.filter_map(|entry| entry.retry_of.map(|target| (target, entry.seq)))
|
||||||
|
.collect();
|
||||||
|
let entries = self.entries[start..end]
|
||||||
|
.iter()
|
||||||
|
.map(|entry| (entry.clone(), retried_by.get(&entry.seq).copied()))
|
||||||
|
.collect();
|
||||||
|
Page { entries, older: (start > 0).then_some(start as u64 + 1) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn new(turn: &str, submission: u32, text: &str) -> NewEntry {
|
||||||
|
NewEntry {
|
||||||
|
turn_id: turn.into(),
|
||||||
|
submission,
|
||||||
|
text: text.into(),
|
||||||
|
narration: Some(format!("story of {text}")),
|
||||||
|
question: None,
|
||||||
|
refusal: None,
|
||||||
|
fault: None,
|
||||||
|
status: TurnStatus::Committed,
|
||||||
|
world_revision: Some(7),
|
||||||
|
retry_of: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn entries_append_page_newest_last_and_survive_a_reopen() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let path = directory.path().join("turn-log-v1.cc");
|
||||||
|
{
|
||||||
|
let mut log = TurnLog::open(&path).unwrap();
|
||||||
|
assert_eq!(log.last_seq(), 0);
|
||||||
|
for n in 1..=5 {
|
||||||
|
assert_eq!(log.record(new(&format!("t{n}"), 1, &format!("say {n}"))).unwrap(), Some(n));
|
||||||
|
assert_eq!(log.last_seq(), n);
|
||||||
|
}
|
||||||
|
assert_eq!(log.record(new("t3", 1, "say 3 again")).unwrap(), None, "a recorded submission is never rewritten");
|
||||||
|
let newest = log.page(None, 2);
|
||||||
|
assert_eq!(newest.entries.iter().map(|(e, _)| e.seq).collect::<Vec<_>>(), [4, 5]);
|
||||||
|
assert_eq!(newest.older, Some(4));
|
||||||
|
let older = log.page(newest.older, 2);
|
||||||
|
assert_eq!(older.entries.iter().map(|(e, _)| e.seq).collect::<Vec<_>>(), [2, 3]);
|
||||||
|
let oldest = log.page(older.older, 2);
|
||||||
|
assert_eq!(oldest.entries.iter().map(|(e, _)| e.seq).collect::<Vec<_>>(), [1]);
|
||||||
|
assert_eq!(oldest.older, None);
|
||||||
|
}
|
||||||
|
let log = TurnLog::open(&path).unwrap();
|
||||||
|
let all = log.page(None, 50);
|
||||||
|
assert_eq!(all.entries.len(), 5);
|
||||||
|
assert_eq!(all.entries[2].0.text, "say 3", "the first write stands");
|
||||||
|
assert_eq!(all.entries[2].0.narration.as_deref(), Some("story of say 3"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_retry_is_a_new_entry_and_the_old_one_reads_as_superseded() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let mut log = TurnLog::open(directory.path().join("turn-log-v1.cc")).unwrap();
|
||||||
|
let mut faulted = new("t1", 1, "I knock");
|
||||||
|
faulted.status = TurnStatus::Faulted;
|
||||||
|
faulted.narration = None;
|
||||||
|
faulted.fault = Some("the storyteller lost the thread".into());
|
||||||
|
log.record(faulted).unwrap();
|
||||||
|
let mut retry = new("t2", 1, "I knock");
|
||||||
|
retry.retry_of = Some(1);
|
||||||
|
log.record(retry).unwrap();
|
||||||
|
let page = log.page(None, 10);
|
||||||
|
assert_eq!(page.entries[0].0.status, TurnStatus::Faulted, "the old entry stays as it was");
|
||||||
|
assert_eq!(page.entries[0].1, Some(2), "and reads as superseded by the retry");
|
||||||
|
assert_eq!(page.entries[1].1, None);
|
||||||
|
let mut bad = new("t3", 1, "x");
|
||||||
|
bad.retry_of = Some(99);
|
||||||
|
assert!(log.record(bad).is_err(), "a retry must name an entry the log holds");
|
||||||
|
}
|
||||||
|
}
|
||||||
249
crates/ghostlight-dungeon/src/vaults.rs
Normal file
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());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
398
crates/ghostlight-dungeon/src/verbs.rs
Normal file
398
crates/ghostlight-dungeon/src/verbs.rs
Normal file
|
|
@ -0,0 +1,398 @@
|
||||||
|
//! The Dungeon's verbs: the affordance catalog every world Begin makes
|
||||||
|
//! declares, and the grant of it to every person.
|
||||||
|
//!
|
||||||
|
//! A fresh world knows only Speak. A deed the player may attempt but the world
|
||||||
|
//! cannot lower is a gap, so the Dungeon declares the deeds a table is made of:
|
||||||
|
//! attack, threaten and accuse. Each lowers to kernel effects the
|
||||||
|
//! kernel alone writes: regard in the target (`AdjustAttitude`), pressure
|
||||||
|
//! (`AdvancePressure`). The effects name no consequence
|
||||||
|
//! beyond the deed. Nothing here refuses a verb on grounds of niceness: a
|
||||||
|
//! sword is drawn when the preconditions hold (the target is in the room), and
|
||||||
|
//! what the world does about it is state the table reads, not a rule.
|
||||||
|
//!
|
||||||
|
//! A deed carries its witnesses through the kernel's own display lowering: the
|
||||||
|
//! table commits it with a `display` quote, which becomes a claim the whole room
|
||||||
|
//! holds as `Seen`. Who saw it is therefore kernel state, and the Open
|
||||||
|
//! grievances block of the table view is derived from it.
|
||||||
|
//!
|
||||||
|
//! What answers a deed is the table's judgement, not a rule here. The table
|
||||||
|
//! sees who was wronged, who saw it, which forums cover the doer and whether
|
||||||
|
//! anyone presses or has sworn a reckoning, and gives the office, the kin and
|
||||||
|
//! the witnesses their own turns, ruling pressure (`advance_pressure`) or a
|
||||||
|
//! sworn reckoning (`create_commitment`, an obligation with the doer as
|
||||||
|
//! counterparty: the kernel refuses a goal that has one) where it judges the
|
||||||
|
//! world would.
|
||||||
|
//!
|
||||||
|
//! Seams, recorded rather than patched:
|
||||||
|
//! - An institution that must react off-screen, with no person of it in the
|
||||||
|
//! room, is the Gestalt hierarchy's turn (`cut-gestalt-*`, not built). No
|
||||||
|
//! scheduler stands in for it here.
|
||||||
|
//! - Verbs are granted to the people a Begin holds. A person an Active
|
||||||
|
//! elaborator authors later holds only what its author grants by id.
|
||||||
|
//! - Steal, give, trade, seduce, persuade, flee, hide and move are not
|
||||||
|
//! declared: a seeded world holds no custody to transfer, and the others
|
||||||
|
//! lower to speech or to nothing the table cannot already rule.
|
||||||
|
|
||||||
|
use ghostlight::{DecodedBatch, SubjectKind, WorldSnapshot, decode_authoring_calls};
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
|
/// The deed kinds this catalog declares, in the order declared.
|
||||||
|
pub(crate) const VERBS: [&str; 3] = ["attack", "threaten", "accuse"];
|
||||||
|
|
||||||
|
fn subject_role() -> Value {
|
||||||
|
json!({"namespace": "subject", "kind": null})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn adjust(delta: i16) -> Value {
|
||||||
|
json!({"op_kind": {"op": "adjust_attitude", "delta": delta, "decay": null}, "roles": ["target"], "bounds": {"bound": "none"}})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn colocated_target() -> Value {
|
||||||
|
json!({"precondition": "can_reach", "subject": "target", "via": "colocated"})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The declarations, as the authoring calls the Dungeon Master would make.
|
||||||
|
fn declarations() -> Vec<(&'static str, Value)> {
|
||||||
|
vec![
|
||||||
|
(
|
||||||
|
"declare_affordance",
|
||||||
|
// Three grades of harm, weighted so a blow usually lands. The
|
||||||
|
// regard the target holds of the actor falls by the grade; what the
|
||||||
|
// wound or death means is the table's ruling.
|
||||||
|
json!({
|
||||||
|
"handle": "attack",
|
||||||
|
"kind": "attack",
|
||||||
|
"roles": [{"role": "target", "kind": subject_role()}],
|
||||||
|
"preconditions": [colocated_target()],
|
||||||
|
"effect_slots": [adjust(-35), adjust(-70), adjust(-100)],
|
||||||
|
"outcome_bands": [
|
||||||
|
{"weight": 3, "effects": [0]},
|
||||||
|
{"weight": 3, "effects": [1]},
|
||||||
|
{"weight": 2, "effects": [2]},
|
||||||
|
],
|
||||||
|
"carries_speech": false,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"declare_affordance",
|
||||||
|
json!({
|
||||||
|
"handle": "threaten",
|
||||||
|
"kind": "threaten",
|
||||||
|
"roles": [{"role": "target", "kind": subject_role()}],
|
||||||
|
"preconditions": [colocated_target()],
|
||||||
|
"effect_slots": [
|
||||||
|
{"op_kind": {"op": "advance_pressure", "by": 20}, "roles": ["target"], "bounds": {"bound": "none"}},
|
||||||
|
adjust(-25),
|
||||||
|
],
|
||||||
|
"outcome_bands": [{"weight": 1, "effects": [0, 1]}],
|
||||||
|
"carries_speech": false,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"declare_affordance",
|
||||||
|
// A grievance carried to someone who can lean on the accused:
|
||||||
|
// pressure on the target from the accuser, who must hold the
|
||||||
|
// charge as something believed. An office answers through its own
|
||||||
|
// people using this same verb.
|
||||||
|
json!({
|
||||||
|
"handle": "accuse",
|
||||||
|
"kind": "accuse",
|
||||||
|
"roles": [
|
||||||
|
{"role": "target", "kind": subject_role()},
|
||||||
|
{"role": "charge", "kind": {"namespace": "entity", "kind": "fact"}},
|
||||||
|
],
|
||||||
|
"preconditions": [{"precondition": "knows", "fact": "charge", "at_least": "believed"}],
|
||||||
|
"effect_slots": [
|
||||||
|
{"op_kind": {"op": "advance_pressure", "by": 25}, "roles": ["target"], "bounds": {"bound": "none"}},
|
||||||
|
],
|
||||||
|
"outcome_bands": [{"weight": 1, "effects": [0]}],
|
||||||
|
"carries_speech": false,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The one patch that declares the catalog and grants it to every person the
|
||||||
|
/// world holds. A world that already carries a verb is a replay of this step
|
||||||
|
/// and is not asked again by the caller.
|
||||||
|
pub(crate) fn install(world: &WorldSnapshot) -> Result<DecodedBatch, String> {
|
||||||
|
let mut calls: Vec<(String, String)> = declarations()
|
||||||
|
.into_iter()
|
||||||
|
.map(|(name, arguments)| (name.to_owned(), arguments.to_string()))
|
||||||
|
.collect();
|
||||||
|
for subject in world
|
||||||
|
.subjects
|
||||||
|
.iter()
|
||||||
|
.filter(|subject| subject.kind == SubjectKind::Person && !subject.retired)
|
||||||
|
{
|
||||||
|
for verb in VERBS {
|
||||||
|
calls.push((
|
||||||
|
"grant_affordance".to_owned(),
|
||||||
|
json!({
|
||||||
|
"subject": {"ref": "existing", "value": subject.id},
|
||||||
|
"affordance": {"ref": "draft", "value": verb},
|
||||||
|
})
|
||||||
|
.to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let borrowed: Vec<(&str, &str)> = calls.iter().map(|(name, arguments)| (name.as_str(), arguments.as_str())).collect();
|
||||||
|
decode_authoring_calls(&borrowed)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use ghostlight::{
|
||||||
|
CommandBody, CommandId, CreateWorldIntent, Lens, LensWeights, PlayPort, PrincipalCommandIntent,
|
||||||
|
SubjectId, VerifiedPrincipalEvidence, WorldMailbox, decode_actor_call, table_view,
|
||||||
|
};
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
struct Scenario {
|
||||||
|
_directory: tempfile::TempDir,
|
||||||
|
world: WorldMailbox,
|
||||||
|
principal: VerifiedPrincipalEvidence,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn text(id: SubjectId) -> String {
|
||||||
|
serde_json::to_value(id).unwrap().as_str().unwrap().to_owned()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn existing(id: impl serde::Serialize) -> Value {
|
||||||
|
json!({"ref": "existing", "value": id})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn snapshot(scene: &Scenario) -> ghostlight::WorldSnapshot {
|
||||||
|
scene.world.snapshot().await.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn who(snapshot: &ghostlight::WorldSnapshot, label: &str) -> SubjectId {
|
||||||
|
snapshot.subjects.iter().find(|subject| subject.label == label).expect("a subject by that label").id
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn submit(scene: &Scenario, body: CommandBody) {
|
||||||
|
let snapshot = snapshot(scene).await;
|
||||||
|
scene
|
||||||
|
.world
|
||||||
|
.submit_principal(
|
||||||
|
PrincipalCommandIntent {
|
||||||
|
id: CommandId::new(),
|
||||||
|
world_id: snapshot.world_id,
|
||||||
|
expected_revision: snapshot.revision,
|
||||||
|
body,
|
||||||
|
},
|
||||||
|
&scene.principal,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn batch(calls: &[(&str, Value)]) -> ghostlight::WorldPatch {
|
||||||
|
let owned: Vec<(&str, String)> = calls.iter().map(|(name, arguments)| (*name, arguments.to_string())).collect();
|
||||||
|
let borrowed: Vec<(&str, &str)> = owned.iter().map(|(name, arguments)| (*name, arguments.as_str())).collect();
|
||||||
|
decode_authoring_calls(&borrowed).expect("the calls decode").patch
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The table's own ruling, through the one door the Dungeon Master holds.
|
||||||
|
async fn rule(scene: &Scenario, calls: &[(&str, Value)]) {
|
||||||
|
PlayPort::new(scene.world.clone()).submit_patch(CommandId::new(), batch(calls)).await.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A tavern with Dorra, her kin Brannoch and a witness, Grix; the Hold's
|
||||||
|
/// watch stands at the gate with Hilda. The player, Korr, is in the tavern.
|
||||||
|
/// Dorra counts Korr a friend, so nothing about the room is hostile.
|
||||||
|
async fn consequence_world() -> Scenario {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let (world, _owner) = WorldMailbox::open(directory.path().join("world.cc")).unwrap();
|
||||||
|
let principal = VerifiedPrincipalEvidence::new("consequence-scenario", chrono::Utc::now() + chrono::Duration::hours(4));
|
||||||
|
let receipt = world
|
||||||
|
.create(
|
||||||
|
CreateWorldIntent {
|
||||||
|
id: CommandId::new(),
|
||||||
|
title: "Consequence Scenario".into(),
|
||||||
|
brief: "A tavern, a gate and a watch.".into(),
|
||||||
|
human_subject_label: "Korr".into(),
|
||||||
|
narrative_persona_label: None,
|
||||||
|
operational_agent_label: None,
|
||||||
|
targets: BTreeMap::new(),
|
||||||
|
jurisdictions: Vec::new(),
|
||||||
|
lens_weights: LensWeights::new(BTreeMap::from([(Lens::Hearth, 1)])),
|
||||||
|
era: None,
|
||||||
|
},
|
||||||
|
&principal,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let scene = Scenario { _directory: directory, world, principal };
|
||||||
|
let start = snapshot(&scene).await;
|
||||||
|
let commons = start.places.iter().find(|place| place.label == "The Commons").unwrap().id;
|
||||||
|
let speak = start.affordances.iter().find(|entry| entry.entry.kind.0 == "speak").unwrap().id;
|
||||||
|
let subject = |handle: &str, label: &str, kind: &str, position: Value| {
|
||||||
|
(
|
||||||
|
"declare_subject",
|
||||||
|
json!({
|
||||||
|
"handle": handle,
|
||||||
|
"label": label,
|
||||||
|
"kind": kind,
|
||||||
|
"controller": {"type": "narrative_persona"},
|
||||||
|
"affordances": [existing(speak)],
|
||||||
|
"position": position,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
let patch = batch(&[
|
||||||
|
("declare_place", json!({"handle": "gate", "label": "The Gate", "container": null})),
|
||||||
|
(
|
||||||
|
"declare_route",
|
||||||
|
json!({"handle": "road", "label": "The Road", "from": existing(commons), "to": {"ref": "draft", "value": "gate"}, "access": {"access": "public"}, "cost": 1}),
|
||||||
|
),
|
||||||
|
subject("dorra", "Dorra Ironkettle", "person", existing(commons)),
|
||||||
|
subject("brann", "Brannoch Deepvein", "person", existing(commons)),
|
||||||
|
subject("grix", "Grix Sparkfinger", "person", existing(commons)),
|
||||||
|
subject("hilda", "Hilda Gatewright", "person", json!({"ref": "draft", "value": "gate"})),
|
||||||
|
subject("watch", "The Deepgate Watch", "institution", json!({"ref": "draft", "value": "gate"})),
|
||||||
|
]);
|
||||||
|
submit(&scene, CommandBody::AdmitPatch { answers: None, patch }).await;
|
||||||
|
let drafted = snapshot(&scene).await;
|
||||||
|
let (dorra, korr) = (who(&drafted, "Dorra Ironkettle"), who(&drafted, "Korr"));
|
||||||
|
submit(
|
||||||
|
&scene,
|
||||||
|
CommandBody::AdmitPatch {
|
||||||
|
answers: None,
|
||||||
|
patch: batch(&[(
|
||||||
|
"declare_attitude",
|
||||||
|
json!({"holder": existing(dorra), "toward": {"toward": "subject", "of": existing(korr)}, "delta": 80, "basis": {"basis": "prejudice"}, "decay": null}),
|
||||||
|
)]),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let drafted = snapshot(&scene).await;
|
||||||
|
submit(&scene, CommandBody::AdmitPatch { answers: None, patch: install(&drafted).unwrap().patch }).await;
|
||||||
|
submit(&scene, CommandBody::ApproveDraft).await;
|
||||||
|
submit(&scene, CommandBody::ActivateWorld).await;
|
||||||
|
let _ = receipt;
|
||||||
|
scene
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn attack(scene: &Scenario, victim: &str, display: &str) -> Result<(), ghostlight::MailboxError> {
|
||||||
|
let now = snapshot(scene).await;
|
||||||
|
let (korr, victim) = (who(&now, "Korr"), who(&now, victim));
|
||||||
|
let arguments = json!({"target": text(victim), "display": display}).to_string();
|
||||||
|
let (opportunity, invocation) = decode_actor_call(&now, korr, "", "attack", &arguments).expect("the player may attack");
|
||||||
|
scene
|
||||||
|
.world
|
||||||
|
.submit_principal(
|
||||||
|
PrincipalCommandIntent {
|
||||||
|
id: CommandId::new(),
|
||||||
|
world_id: now.world_id,
|
||||||
|
expected_revision: now.revision,
|
||||||
|
body: CommandBody::ExerciseDecision { opportunity, invocation },
|
||||||
|
},
|
||||||
|
&scene.principal,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map(|_| ())
|
||||||
|
}
|
||||||
|
|
||||||
|
const DEED: &str = "Korr buries his axe in Dorra.";
|
||||||
|
|
||||||
|
fn open_grievances(view: &str) -> String {
|
||||||
|
view.split("Open grievances").nth(1).unwrap().split("\n Persona material").next().unwrap().to_owned()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn between<'a>(text: &'a str, from: &str, to: &str) -> &'a str {
|
||||||
|
let start = text.find(from).unwrap_or_else(|| panic!("`{from}` not in view")) + from.len();
|
||||||
|
let end = start + text[start..].find(to).unwrap_or(text.len() - start);
|
||||||
|
&text[start..end]
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn nothing_forbids_the_sword_and_the_room_sees_it() {
|
||||||
|
let scene = consequence_world().await;
|
||||||
|
// Dorra is the player's friend, and the attack is admitted all the same.
|
||||||
|
attack(&scene, "Dorra Ironkettle", DEED).await.expect("an attack on a friend is admitted");
|
||||||
|
let view = table_view(&snapshot(&scene).await);
|
||||||
|
let grievances = open_grievances(&view);
|
||||||
|
let seen = between(&grievances, "acts seen by:", "forums covering");
|
||||||
|
for witness in ["Grix Sparkfinger", "Brannoch Deepvein", "Dorra Ironkettle"] {
|
||||||
|
assert!(seen.contains(witness), "{witness} stands in the room and saw it: {seen}");
|
||||||
|
}
|
||||||
|
assert!(!seen.contains("Hilda"), "the gate is out of earshot and out of sight: {seen}");
|
||||||
|
assert!(grievances.contains("Korr"), "{grievances}");
|
||||||
|
assert!(grievances.contains("nothing has answered it yet"), "{grievances}");
|
||||||
|
let subjects = between(&view, "Subjects:", "
|
||||||
|
Affordances");
|
||||||
|
let watch = between(subjects, "The Deepgate Watch [", "holdings");
|
||||||
|
assert!(watch.contains("institution") && !watch.contains("attack"), "an institution is granted no sword: {watch}");
|
||||||
|
let player = between(subjects, "Korr [", "holdings");
|
||||||
|
for verb in VERBS {
|
||||||
|
assert!(player.contains(verb), "the player holds {verb}: {player}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn an_unseen_world_has_no_open_grievance() {
|
||||||
|
let scene = consequence_world().await;
|
||||||
|
assert!(open_grievances(&table_view(&snapshot(&scene).await)).trim().ends_with("none"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn word_spreads_law_presses_and_kin_swear() {
|
||||||
|
let scene = consequence_world().await;
|
||||||
|
attack(&scene, "Dorra Ironkettle", DEED).await.unwrap();
|
||||||
|
let now = snapshot(&scene).await;
|
||||||
|
let view = table_view(&now);
|
||||||
|
let (korr, grix, hilda, brann) =
|
||||||
|
(who(&now, "Korr"), who(&now, "Grix Sparkfinger"), who(&now, "Hilda Gatewright"), who(&now, "Brannoch Deepvein"));
|
||||||
|
let quoted = format!("\"{DEED}\" [");
|
||||||
|
let deed = between(&view, "ed, "]").to_owned();
|
||||||
|
let road = between(&view, "The Road [", "]").to_owned();
|
||||||
|
assert!(!between(&view, &format!("\"{DEED}\" [{deed}]: "), "\n").contains("Hilda"), "the guard has not heard");
|
||||||
|
|
||||||
|
// The witness walks to the gate and tells the guard.
|
||||||
|
rule(&scene, &[("relocate", json!({"subject": existing(grix), "via": existing(road)}))]).await;
|
||||||
|
rule(&scene, &[("communicate", json!({"speaker": existing(grix), "fact": existing(&deed), "to": "colocated"}))]).await;
|
||||||
|
let view = table_view(&snapshot(&scene).await);
|
||||||
|
assert!(between(&view, &format!("\"{DEED}\" [{deed}]: "), "\n").contains("Hilda"), "the guard was told");
|
||||||
|
|
||||||
|
// Believing it, the guard regards the killer worse than a stranger.
|
||||||
|
rule(
|
||||||
|
&scene,
|
||||||
|
&[(
|
||||||
|
"declare_attitude",
|
||||||
|
json!({"holder": existing(hilda), "toward": {"toward": "subject", "of": existing(korr)}, "delta": -60, "basis": {"basis": "rumour", "fact": existing(&deed)}, "decay": null}),
|
||||||
|
)],
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let view = table_view(&snapshot(&scene).await);
|
||||||
|
assert!(between(&view, "Regard (", "Persona material").contains("Hilda Gatewright ["), "{view}");
|
||||||
|
|
||||||
|
// The law leans on the player, and the grievance is no longer unanswered.
|
||||||
|
assert!(open_grievances(&view).contains("nothing has answered it yet"));
|
||||||
|
rule(&scene, &[("advance_pressure", json!({"source": {"from": "subject", "of": existing(hilda)}, "target": existing(korr), "by": 30}))]).await;
|
||||||
|
let pressed = open_grievances(&table_view(&snapshot(&scene).await));
|
||||||
|
assert!(between(&pressed, "pressed by:", "reckonings").contains("Hilda Gatewright"), "{pressed}");
|
||||||
|
assert!(!pressed.contains("nothing has answered it yet"), "{pressed}");
|
||||||
|
|
||||||
|
// The victim's kin swear a reckoning with the player as counterparty.
|
||||||
|
rule(
|
||||||
|
&scene,
|
||||||
|
&[(
|
||||||
|
"create_commitment",
|
||||||
|
json!({"subject": existing(brann), "counterparty": existing(korr), "kind": "obligation", "due": 600, "period": null, "checks": [], "statement": "Make Korr answer for Dorra."}),
|
||||||
|
)],
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let sworn = open_grievances(&table_view(&snapshot(&scene).await));
|
||||||
|
assert!(between(&sworn, "reckonings sworn against them:", "answered").contains("Brannoch Deepvein"), "{sworn}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn no_verb_text_refuses_violence() {
|
||||||
|
let lower = serde_json::to_string(&declarations()).unwrap().to_lowercase();
|
||||||
|
assert!(!lower.contains("not allowed to attack"));
|
||||||
|
assert!(lower.find("refuse").is_none_or(|at| !lower[at..].contains("violence")));
|
||||||
|
assert_eq!(declarations().len(), VERBS.len());
|
||||||
|
}
|
||||||
|
}
|
||||||
1210
crates/ghostlight-dungeon/src/waves.rs
Normal file
1210
crates/ghostlight-dungeon/src/waves.rs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -54,6 +54,19 @@ 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,
|
||||||
|
/// What the player wrote this turn: the player's own act, which is not in their own knowledge.
|
||||||
|
pub player_turn: &'a str,
|
||||||
|
pub visible_stimulus: &'a str,
|
||||||
|
pub domain_guidance: &'a str,
|
||||||
|
pub word_budget: usize,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
#[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 +106,43 @@ pub fn build_projector_prompt(input: &ProjectorPrompt<'_>) -> String {
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The storyteller's contract: it tells the player, in second person, what just
|
||||||
|
/// happened and where they now stand, and is never the player or anyone else in
|
||||||
|
/// the story. It is handed facts and told to tell a story from them: the
|
||||||
|
/// context and stimulus are material, not a form to be read down.
|
||||||
|
pub fn build_narrator_prompt(input: &NarratorPrompt<'_>) -> String {
|
||||||
|
format!(
|
||||||
|
"<!-- membrane:{MEMBRANE_SCHEMA}:narrator -->
|
||||||
|
You are the storyteller of a long-running tale, telling the player what has just happened and where they now stand. The player's character is {player}. Speak to the player in the second person, present tense (\"You turn to Mira...\"); never in the first person, and never as {player} or any other character.
|
||||||
|
|
||||||
|
Tell it the way a storyteller at a table would, in a few short paragraphs of plain prose:
|
||||||
|
- Begin with what the player just did, in their own words where they spoke, as theirs (\"You ask...\"), then give what came of it. When people answered or acted, let them: render each reply in that person's own voice, quoting their words exactly as the visible stimulus gives them, with a gesture or a beat of stage business around it, never summarised. Do not invent replies; if no one has answered, say who is looking at you, waiting, or turning away.
|
||||||
|
- Then settle the scene: who is here and what they are doing, the feel of the place, and the ways out worked in naturally (\"the passage toward the Ironmarket\"), the way a person standing there would notice them.
|
||||||
|
- Tell only what the facts below establish. Name only the people, places and routes they name; invent none, and do not say what lies beyond an exit. What the facts leave out is simply not told: never remark that something is unknown, absent, empty or missing, never list what the player has, holds, lacks or has not promised, and never give a number, a count or a cost.
|
||||||
|
- Do not recite. Do not list what the player could do next or close on a menu of options; do not choose actions for the player, expose field names, or claim effects in the world.
|
||||||
|
|
||||||
|
Domain guidance:
|
||||||
|
{guidance}
|
||||||
|
|
||||||
|
Facts about where the player stands:
|
||||||
|
{context}
|
||||||
|
|
||||||
|
What the player did this turn, in their own words:
|
||||||
|
{player_turn}
|
||||||
|
|
||||||
|
What the player has seen and heard (rows marked new are the most recent):
|
||||||
|
{stimulus}
|
||||||
|
|
||||||
|
Use at most {word_budget} words; fewer is better. Return only the telling.",
|
||||||
|
player = input.player,
|
||||||
|
guidance = input.domain_guidance,
|
||||||
|
context = input.typed_context,
|
||||||
|
player_turn = input.player_turn,
|
||||||
|
stimulus = input.visible_stimulus,
|
||||||
|
word_budget = input.word_budget,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
pub fn build_persona_prompt(input: &PersonaPrompt<'_>) -> String {
|
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.",
|
||||||
|
|
|
||||||
15
crates/ghostlight-verse/Cargo.toml
Normal file
15
crates/ghostlight-verse/Cargo.toml
Normal file
|
|
@ -0,0 +1,15 @@
|
||||||
|
[package]
|
||||||
|
name = "ghostlight-verse"
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
anyhow.workspace = true
|
||||||
|
chrono.workspace = true
|
||||||
|
ghostlight = { path = "../ghostlight" }
|
||||||
|
tokio.workspace = true
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
serde_json.workspace = true
|
||||||
|
tempfile = "3"
|
||||||
407
crates/ghostlight-verse/src/main.rs
Normal file
407
crates/ghostlight-verse/src/main.rs
Normal file
|
|
@ -0,0 +1,407 @@
|
||||||
|
//! The verse runner's operator command line.
|
||||||
|
//!
|
||||||
|
//! `genesis` creates the canonical Aetheria verse world in a state root, and
|
||||||
|
//! `run` advances it a given number of ticks under a token cap, printing per
|
||||||
|
//! tick what each faction did and what it cost. A run starts only when this
|
||||||
|
//! command is invoked, and ends when it has done what it was asked.
|
||||||
|
//!
|
||||||
|
//! The state root holds `world.cc`, `controller-work.cc`, `runs.cc` and
|
||||||
|
//! `calls.cc`. The provider key is read from a file at run time and appears
|
||||||
|
//! nowhere else.
|
||||||
|
|
||||||
|
use anyhow::{Context, Result, anyhow, bail};
|
||||||
|
use chrono::{Duration, Utc};
|
||||||
|
use ghostlight::{
|
||||||
|
CommandBody, CommandId, ControllerModels, ControllerOpenError, ControllerRunner, DEFAULT_HOSTED_MODEL_PREFIX,
|
||||||
|
DEFAULT_LOCAL_MODEL_PREFIX, CallRecordStore, CoverBudget, CreateVerseWorldIntent,
|
||||||
|
GestaltKnobs, HostedBinding, LaneTokens, Lens, LensWeights, LocalBinding, PrincipalCommandIntent, RecordingInferencePort,
|
||||||
|
RunStart, RunStatus, TickMinutes, VerifiedPrincipalEvidence, VerseRunConfig, VerseRunStore,
|
||||||
|
WorldMailbox, call_run_id, id_text, open_controller_work, open_inference,
|
||||||
|
read_aetheria_catalog, run_manual,
|
||||||
|
};
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
use std::ops::ControlFlow;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::process::ExitCode;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
|
||||||
|
/// The default knobs' cover: what a manual run spends per tick on cognition
|
||||||
|
/// cells inside one node. The operator's lever on cost is the token cap; the
|
||||||
|
/// partition covers every voice of a due node.
|
||||||
|
const COVER: CoverBudget = CoverBudget {
|
||||||
|
cells: 8,
|
||||||
|
constituent_cap: 8,
|
||||||
|
urgency_slots: 2,
|
||||||
|
};
|
||||||
|
/// Default depth: only the root is open, so every faction speaks as a voice
|
||||||
|
/// of one node at the tick's own rate, the shape of the flat cover.
|
||||||
|
const DEPTH: u8 = 1;
|
||||||
|
/// Default node-turn bound per tick: far above the world's node count.
|
||||||
|
const MAX_NODE_TURNS: u16 = 256;
|
||||||
|
|
||||||
|
const RUNTIME_ID: &str = "ghostlight-verse";
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> ExitCode {
|
||||||
|
let arguments: Vec<String> = std::env::args().skip(1).collect();
|
||||||
|
match command(arguments).await {
|
||||||
|
Ok(code) => code,
|
||||||
|
Err(error) => {
|
||||||
|
eprintln!("ghostlight-verse: {error:#}");
|
||||||
|
ExitCode::FAILURE
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn command(arguments: Vec<String>) -> Result<ExitCode> {
|
||||||
|
let Some((name, rest)) = arguments.split_first() else {
|
||||||
|
bail!("usage: ghostlight-verse genesis|run [flags]");
|
||||||
|
};
|
||||||
|
match name.as_str() {
|
||||||
|
"genesis" => genesis(Flags::parse(rest, &GENESIS_FLAGS)?).await,
|
||||||
|
"run" => run(Flags::parse(rest, &RUN_FLAGS)?).await,
|
||||||
|
_ => bail!("unknown command, expected genesis or run"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const GENESIS_FLAGS: [&str; 4] = ["catalog", "aetheria-commit", "state", "owner-hash"];
|
||||||
|
const RUN_FLAGS: [&str; 9] = [
|
||||||
|
"state",
|
||||||
|
"ticks",
|
||||||
|
"token-cap",
|
||||||
|
"tick-span-minutes",
|
||||||
|
"model",
|
||||||
|
"base-url",
|
||||||
|
"key-file",
|
||||||
|
"depth",
|
||||||
|
"band",
|
||||||
|
];
|
||||||
|
/// Flags a command may omit.
|
||||||
|
const OPTIONAL: [&str; 3] = ["key-file", "depth", "band"];
|
||||||
|
/// Flags that may be given more than once.
|
||||||
|
const REPEATABLE: [&str; 1] = ["band"];
|
||||||
|
|
||||||
|
/// `--name value` pairs from the command's own list, each named once unless it
|
||||||
|
/// is repeatable, in which case its values keep the order given.
|
||||||
|
struct Flags(BTreeMap<&'static str, Vec<String>>);
|
||||||
|
|
||||||
|
impl Flags {
|
||||||
|
fn parse(arguments: &[String], allowed: &[&'static str]) -> Result<Self> {
|
||||||
|
let mut seen: BTreeMap<&'static str, Vec<String>> = BTreeMap::new();
|
||||||
|
let mut rest = arguments.iter();
|
||||||
|
while let Some(flag) = rest.next() {
|
||||||
|
let Some(name) = flag.strip_prefix("--") else {
|
||||||
|
bail!("expected a --flag, found a bare argument");
|
||||||
|
};
|
||||||
|
let Some(&known) = allowed.iter().find(|candidate| **candidate == name) else {
|
||||||
|
bail!("a flag this command does not take was given");
|
||||||
|
};
|
||||||
|
let Some(value) = rest.next() else {
|
||||||
|
bail!("--{known} needs a value");
|
||||||
|
};
|
||||||
|
let values = seen.entry(known).or_default();
|
||||||
|
if !values.is_empty() && !REPEATABLE.contains(&known) {
|
||||||
|
bail!("--{known} was given twice");
|
||||||
|
}
|
||||||
|
values.push(value.clone());
|
||||||
|
}
|
||||||
|
for &required in allowed {
|
||||||
|
if !OPTIONAL.contains(&required) && !seen.contains_key(required) {
|
||||||
|
bail!("--{required} is required");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Self(seen))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn text(&self, name: &str) -> &str {
|
||||||
|
self.0.get(name).and_then(|values| values.first()).map_or("", String::as_str)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn all(&self, name: &str) -> &[String] {
|
||||||
|
self.0.get(name).map_or(&[], Vec::as_slice)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn path(&self, name: &str) -> PathBuf {
|
||||||
|
PathBuf::from(self.text(name))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn number<T: std::str::FromStr + PartialOrd + Default>(&self, name: &str) -> Result<T> {
|
||||||
|
match self.text(name).parse::<T>() {
|
||||||
|
Ok(value) if value > T::default() => Ok(value),
|
||||||
|
_ => bail!("--{name} is not a positive integer"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The run's knobs: the flags over the defaults. With no `--band` the one band
|
||||||
|
/// is the tick span; `--band DIST=MINUTES` gives the period of the nodes
|
||||||
|
/// DIST hops from the focus (the last band is the rest, and a verse tick has no
|
||||||
|
/// focus, so only that one governs). Bands must be given for distances 0, 1, 2
|
||||||
|
/// and so on, with no gap.
|
||||||
|
fn knobs(flags: &Flags, tick_span: TickMinutes) -> Result<GestaltKnobs> {
|
||||||
|
let depth = if flags.0.contains_key("depth") {
|
||||||
|
flags.number::<u8>("depth")?
|
||||||
|
} else {
|
||||||
|
DEPTH
|
||||||
|
};
|
||||||
|
let mut given: BTreeMap<usize, TickMinutes> = BTreeMap::new();
|
||||||
|
for band in flags.all("band") {
|
||||||
|
let parsed = band.split_once('=').and_then(|(distance, minutes)| {
|
||||||
|
Some((distance.parse::<usize>().ok()?, TickMinutes::new(minutes.parse().ok()?)?))
|
||||||
|
});
|
||||||
|
let Some((distance, minutes)) = parsed else {
|
||||||
|
bail!("--band is not DIST=MINUTES with a minutes value inside the clock's span");
|
||||||
|
};
|
||||||
|
if given.insert(distance, minutes).is_some() {
|
||||||
|
bail!("--band names one distance twice");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let bands = if given.is_empty() {
|
||||||
|
vec![tick_span]
|
||||||
|
} else if given.keys().copied().eq(0..given.len()) {
|
||||||
|
given.into_values().collect()
|
||||||
|
} else {
|
||||||
|
bail!("--band must name distances 0, 1, 2 and so on without a gap");
|
||||||
|
};
|
||||||
|
Ok(GestaltKnobs {
|
||||||
|
bands,
|
||||||
|
depth,
|
||||||
|
max_node_turns: MAX_NODE_TURNS,
|
||||||
|
cover: COVER,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn genesis(flags: Flags) -> Result<ExitCode> {
|
||||||
|
let state = flags.path("state");
|
||||||
|
std::fs::create_dir_all(&state).context("the state directory cannot be created")?;
|
||||||
|
let catalog = read_aetheria_catalog(flags.path("catalog"))
|
||||||
|
.context("the Aetheria catalog cannot be read")?;
|
||||||
|
let factions = catalog.factions.len();
|
||||||
|
let principal = VerifiedPrincipalEvidence::new(flags.text("owner-hash"), Utc::now() + Duration::hours(1));
|
||||||
|
|
||||||
|
let (mailbox, task) = WorldMailbox::open(state.join("world.cc"))
|
||||||
|
.map_err(store_fault("the world file in --state cannot be opened"))?;
|
||||||
|
let receipt = mailbox
|
||||||
|
.create_verse(
|
||||||
|
CreateVerseWorldIntent {
|
||||||
|
id: CommandId::new(),
|
||||||
|
title: "The Aetheria Verse".into(),
|
||||||
|
brief: "The Aetheria verse, simulated from its catalog.".into(),
|
||||||
|
catalog,
|
||||||
|
aetheria_commit: flags.text("aetheria-commit").into(),
|
||||||
|
lens_weights: LensWeights::new(Lens::ALL.into_iter().map(|lens| (lens, 1)).collect()),
|
||||||
|
targets: BTreeMap::new(),
|
||||||
|
},
|
||||||
|
&principal,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.context("the verse world cannot be created")?;
|
||||||
|
// A created world is a draft: the owner approves and activates it, so the
|
||||||
|
// factions hold opportunities.
|
||||||
|
for body in [CommandBody::ApproveDraft, CommandBody::ActivateWorld] {
|
||||||
|
let revision = mailbox.snapshot().await.context("the world cannot be read")?.revision;
|
||||||
|
mailbox
|
||||||
|
.submit_principal(
|
||||||
|
PrincipalCommandIntent {
|
||||||
|
id: CommandId::new(),
|
||||||
|
world_id: receipt.world_id,
|
||||||
|
expected_revision: revision,
|
||||||
|
body,
|
||||||
|
},
|
||||||
|
&principal,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.context("the world cannot be activated")?;
|
||||||
|
}
|
||||||
|
drop(mailbox);
|
||||||
|
task.await.context("the world file did not close cleanly")?;
|
||||||
|
println!("world {}", id_text(receipt.world_id));
|
||||||
|
println!("factions {factions}");
|
||||||
|
println!("phase Active");
|
||||||
|
Ok(ExitCode::SUCCESS)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn run(flags: Flags) -> Result<ExitCode> {
|
||||||
|
let state = flags.path("state");
|
||||||
|
let ticks: u32 = flags.number("ticks")?;
|
||||||
|
let cap: u64 = flags.number("token-cap")?;
|
||||||
|
let span: u32 = flags.number("tick-span-minutes")?;
|
||||||
|
let tick_span = TickMinutes::new(span).context("--tick-span-minutes is outside the clock's span")?;
|
||||||
|
let knobs = knobs(&flags, tick_span)?;
|
||||||
|
if !state.join("world.cc").is_file() {
|
||||||
|
bail!("the state directory holds no world; run genesis first");
|
||||||
|
}
|
||||||
|
|
||||||
|
let model = flags.text("model").to_owned();
|
||||||
|
let models = ControllerModels {
|
||||||
|
projector: model.clone(),
|
||||||
|
persona: model.clone(),
|
||||||
|
interpreter: model.clone(),
|
||||||
|
operational_agent: model.clone(),
|
||||||
|
elaborator: model.clone(),
|
||||||
|
};
|
||||||
|
let inner = open_lane(&flags, &model, &models)?;
|
||||||
|
|
||||||
|
let (mailbox, task) = WorldMailbox::open(state.join("world.cc"))
|
||||||
|
.map_err(store_fault("the world file in --state cannot be opened"))?;
|
||||||
|
let world = mailbox.snapshot().await.context("the world cannot be read")?;
|
||||||
|
let calls = Arc::new(CallRecordStore::open(state.join("calls.cc")).map_err(store_fault("the call records in --state cannot be opened"))?);
|
||||||
|
let runs = VerseRunStore::open(state.join("runs.cc")).map_err(store_fault("the run records in --state cannot be opened"))?;
|
||||||
|
let work = open_controller_work(state.join("controller-work.cc"))
|
||||||
|
.map_err(store_fault("the controller work store in --state cannot be opened"))?;
|
||||||
|
let config = VerseRunConfig {
|
||||||
|
ticks,
|
||||||
|
tick_span,
|
||||||
|
knobs,
|
||||||
|
};
|
||||||
|
let claim = runs
|
||||||
|
.claim(&world, cap, &config)
|
||||||
|
.context("the run cannot be claimed")?;
|
||||||
|
let sequence = claim.sequence();
|
||||||
|
// A start that fails after the claim ends the claimed run, so it binds
|
||||||
|
// nothing: the next claim takes the next number.
|
||||||
|
let started = RecordingInferencePort::open(
|
||||||
|
inner,
|
||||||
|
calls,
|
||||||
|
call_run_id(sequence),
|
||||||
|
cap,
|
||||||
|
// The run's token cap is the wave lane's allowance; the verse runs no
|
||||||
|
// elaborator, so that lane has none.
|
||||||
|
LaneTokens {
|
||||||
|
wave: cap,
|
||||||
|
elaboration: 0,
|
||||||
|
},
|
||||||
|
&RunStart::of(&world),
|
||||||
|
)
|
||||||
|
.context("the run's call records cannot be opened")
|
||||||
|
.and_then(|port| {
|
||||||
|
let port = Arc::new(port);
|
||||||
|
ControllerRunner::open(mailbox.clone(), port.clone(), work, models)
|
||||||
|
.map(|runner| (port, runner))
|
||||||
|
.context("the controller organ cannot open")
|
||||||
|
});
|
||||||
|
let (port, runner) = match started {
|
||||||
|
Ok(started) => started,
|
||||||
|
Err(error) => {
|
||||||
|
return Err(match runs.abandon(claim, "start_refused") {
|
||||||
|
Ok(()) => error,
|
||||||
|
Err(_) => error.context("the refused run's record could not be ended"),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
println!(
|
||||||
|
"run {sequence}: {ticks} ticks of {span} minutes, cap {cap} tokens, model {model}"
|
||||||
|
);
|
||||||
|
let interrupted = Arc::new(AtomicBool::new(false));
|
||||||
|
{
|
||||||
|
let interrupted = interrupted.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
if tokio::signal::ctrl_c().await.is_ok() {
|
||||||
|
interrupted.store(true, Ordering::SeqCst);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let outcome = run_manual(
|
||||||
|
&mailbox,
|
||||||
|
&runner,
|
||||||
|
&port,
|
||||||
|
&runs,
|
||||||
|
claim,
|
||||||
|
&config,
|
||||||
|
|report| {
|
||||||
|
print!("{report}");
|
||||||
|
if interrupted.load(Ordering::SeqCst) {
|
||||||
|
ControlFlow::Break(())
|
||||||
|
} else {
|
||||||
|
ControlFlow::Continue(())
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.context("the run could not be recorded")?;
|
||||||
|
println!(
|
||||||
|
"status: {}; {} of {} ticks closed",
|
||||||
|
outcome.record.status,
|
||||||
|
outcome.record.ticks_closed(),
|
||||||
|
outcome.record.ticks_requested
|
||||||
|
);
|
||||||
|
drop(runner);
|
||||||
|
drop(port);
|
||||||
|
drop(mailbox);
|
||||||
|
task.await.context("the world file did not close cleanly")?;
|
||||||
|
Ok(match outcome.record.status {
|
||||||
|
RunStatus::Failed { .. } => ExitCode::FAILURE,
|
||||||
|
_ => ExitCode::SUCCESS,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The inference lane the model's prefix names. A hosted model needs an https
|
||||||
|
/// origin and a key file; a local one reaches a loopback server and needs
|
||||||
|
/// neither, so a key file beside it is refused.
|
||||||
|
fn open_lane(
|
||||||
|
flags: &Flags,
|
||||||
|
model: &str,
|
||||||
|
models: &ControllerModels,
|
||||||
|
) -> Result<Arc<dyn ghostlight::InferencePort>> {
|
||||||
|
let (mut hosted, mut local) = (None, None);
|
||||||
|
if model.starts_with(DEFAULT_HOSTED_MODEL_PREFIX) {
|
||||||
|
let Some(key) = flags.0.get("key-file").and_then(|values| values.first()) else {
|
||||||
|
bail!("a hosted model needs --key-file");
|
||||||
|
};
|
||||||
|
hosted = Some(HostedBinding {
|
||||||
|
base_url: flags.text("base-url").to_owned(),
|
||||||
|
key_path: Path::new(key).to_owned(),
|
||||||
|
model_prefix: DEFAULT_HOSTED_MODEL_PREFIX.into(),
|
||||||
|
caller_runtime_id: RUNTIME_ID.into(),
|
||||||
|
});
|
||||||
|
} else if model.starts_with(DEFAULT_LOCAL_MODEL_PREFIX) {
|
||||||
|
if flags.0.contains_key("key-file") {
|
||||||
|
bail!("a local model takes no --key-file");
|
||||||
|
}
|
||||||
|
let endpoint: SocketAddr = flags
|
||||||
|
.text("base-url")
|
||||||
|
.strip_prefix("http://")
|
||||||
|
.and_then(|address| address.trim_end_matches('/').parse().ok())
|
||||||
|
.context("--base-url for a local model is not http://<address>:<port>")?;
|
||||||
|
local = Some(LocalBinding {
|
||||||
|
endpoint,
|
||||||
|
model_prefix: DEFAULT_LOCAL_MODEL_PREFIX.into(),
|
||||||
|
caller_runtime_id: RUNTIME_ID.into(),
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
bail!("--model names no inference lane (expected a hosted/ or local/ prefix)");
|
||||||
|
}
|
||||||
|
open_inference(None, local, hosted, &models.each())
|
||||||
|
.map_err(|error| anyhow!(lane_fault(&error)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A store that cannot open says which one and that it is under `--state`,
|
||||||
|
/// never the path or the store's own text, which carries the path.
|
||||||
|
fn store_fault<E>(message: &'static str) -> impl FnOnce(E) -> anyhow::Error {
|
||||||
|
move |_| anyhow!(message)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a lane that cannot open says: the flag or the kind of fault, never a
|
||||||
|
/// value the operator passed.
|
||||||
|
fn lane_fault(error: &ControllerOpenError) -> &'static str {
|
||||||
|
match error {
|
||||||
|
ControllerOpenError::InvalidModels => "--model is not an exact nonempty identifier",
|
||||||
|
ControllerOpenError::Connector(_) => "the connector lane cannot open",
|
||||||
|
ControllerOpenError::WorkStore(_) => "the controller work journal cannot open",
|
||||||
|
ControllerOpenError::UnroutableModel { .. } => "--model is claimed by no inference lane",
|
||||||
|
ControllerOpenError::LocalEndpointNotLoopback { .. } => {
|
||||||
|
"--base-url for a local model must be a loopback address"
|
||||||
|
}
|
||||||
|
ControllerOpenError::HostedEndpointNotHttps => {
|
||||||
|
"--base-url for a hosted model must be an https URL"
|
||||||
|
}
|
||||||
|
ControllerOpenError::HostedKeyUnreadable => {
|
||||||
|
"--key-file is unreadable, empty, or not one run of visible ASCII"
|
||||||
|
}
|
||||||
|
ControllerOpenError::SharedModelPrefix { .. } => "two inference lanes claim one model prefix",
|
||||||
|
ControllerOpenError::EmptyModelPrefix { .. } => "an inference lane's model prefix is empty",
|
||||||
|
}
|
||||||
|
}
|
||||||
490
crates/ghostlight-verse/tests/verse_binary.rs
Normal file
490
crates/ghostlight-verse/tests/verse_binary.rs
Normal file
|
|
@ -0,0 +1,490 @@
|
||||||
|
//! The `ghostlight-verse` command against a loopback scripted responder. No
|
||||||
|
//! real model is called and no key file is read: the responder answers the
|
||||||
|
//! OpenAI-compatible chat-completions request the local lane sends.
|
||||||
|
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
use std::io::{Read, Write};
|
||||||
|
use std::net::{SocketAddr, TcpListener, TcpStream};
|
||||||
|
use std::path::Path;
|
||||||
|
use std::process::{Command, Output};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||||
|
|
||||||
|
const BINARY: &str = env!("CARGO_BIN_EXE_ghostlight-verse");
|
||||||
|
const CATALOG: &str = concat!(
|
||||||
|
env!("CARGO_MANIFEST_DIR"),
|
||||||
|
"/../ghostlight/tests/fixtures/aetheria-verse-catalog.cc"
|
||||||
|
);
|
||||||
|
const COMMIT: &str = "92b82e9aa5bb422c568c4bfc85a8f641426a41fc";
|
||||||
|
/// What the responder reports each call cost: 120 prompt and 30 completion.
|
||||||
|
const PER_CALL: u64 = 150;
|
||||||
|
|
||||||
|
fn verse(arguments: &[&str]) -> Output {
|
||||||
|
Command::new(BINARY).args(arguments).output().unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn stdout(output: &Output) -> String {
|
||||||
|
String::from_utf8_lossy(&output.stdout).into_owned()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn stderr(output: &Output) -> String {
|
||||||
|
String::from_utf8_lossy(&output.stderr).into_owned()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn genesis(state: &Path) -> Output {
|
||||||
|
verse(&[
|
||||||
|
"genesis",
|
||||||
|
"--catalog",
|
||||||
|
CATALOG,
|
||||||
|
"--aetheria-commit",
|
||||||
|
COMMIT,
|
||||||
|
"--state",
|
||||||
|
state.to_str().unwrap(),
|
||||||
|
"--owner-hash",
|
||||||
|
"verse-owner",
|
||||||
|
])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Answers every chat-completions request with one tool call: the faction the
|
||||||
|
/// prompt names speaks its own line. Counts the requests it served.
|
||||||
|
struct Responder {
|
||||||
|
address: SocketAddr,
|
||||||
|
served: Arc<AtomicUsize>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Responder {
|
||||||
|
fn start() -> Self {
|
||||||
|
Self::answering(200)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A provider that refuses every call with this status.
|
||||||
|
fn refusing(status: u16) -> Self {
|
||||||
|
Self::answering(status)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn answering(status: u16) -> Self {
|
||||||
|
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||||
|
let address = listener.local_addr().unwrap();
|
||||||
|
let served = Arc::new(AtomicUsize::new(0));
|
||||||
|
let counter = served.clone();
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
for stream in listener.incoming() {
|
||||||
|
let Ok(stream) = stream else { return };
|
||||||
|
let counter = counter.clone();
|
||||||
|
std::thread::spawn(move || serve(stream, &counter, status));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Self { address, served }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn url(&self) -> String {
|
||||||
|
format!("http://{}", self.address)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serve(mut stream: TcpStream, served: &AtomicUsize, status: u16) {
|
||||||
|
let mut raw = Vec::new();
|
||||||
|
let mut chunk = [0u8; 4096];
|
||||||
|
let (head_end, length) = loop {
|
||||||
|
let read = stream.read(&mut chunk).unwrap_or(0);
|
||||||
|
if read == 0 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
raw.extend_from_slice(&chunk[..read]);
|
||||||
|
if let Some(end) = raw.windows(4).position(|window| window == b"\r\n\r\n") {
|
||||||
|
let head = String::from_utf8_lossy(&raw[..end]).to_ascii_lowercase();
|
||||||
|
let length = head
|
||||||
|
.lines()
|
||||||
|
.find_map(|line| line.strip_prefix("content-length:"))
|
||||||
|
.and_then(|value| value.trim().parse::<usize>().ok())
|
||||||
|
.unwrap_or(0);
|
||||||
|
break (end + 4, length);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
while raw.len() < head_end + length {
|
||||||
|
let read = stream.read(&mut chunk).unwrap_or(0);
|
||||||
|
if read == 0 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
raw.extend_from_slice(&chunk[..read]);
|
||||||
|
}
|
||||||
|
let request: Value = serde_json::from_slice(&raw[head_end..head_end + length]).unwrap();
|
||||||
|
let text = request.to_string();
|
||||||
|
let faction = ["Adrasteia", "Brannoch"]
|
||||||
|
.into_iter()
|
||||||
|
.find(|name| text.contains(&format!("Decision owner:\\n{name}\\n")))
|
||||||
|
.expect("a request names its faction");
|
||||||
|
let sequence = served.fetch_add(1, Ordering::SeqCst);
|
||||||
|
let reply = json!({
|
||||||
|
"id": format!("reply-{sequence}"),
|
||||||
|
"choices": [{
|
||||||
|
"message": {
|
||||||
|
"role": "assistant",
|
||||||
|
"content": null,
|
||||||
|
"tool_calls": [{
|
||||||
|
"id": format!("call-{sequence}"),
|
||||||
|
"type": "function",
|
||||||
|
"function": {
|
||||||
|
"name": "speak",
|
||||||
|
"arguments": json!({ "text": format!("{faction} holds the line.") }).to_string(),
|
||||||
|
},
|
||||||
|
}],
|
||||||
|
},
|
||||||
|
"finish_reason": "tool_calls",
|
||||||
|
}],
|
||||||
|
"usage": { "prompt_tokens": 120, "completion_tokens": 30 },
|
||||||
|
})
|
||||||
|
.to_string();
|
||||||
|
let response = format!(
|
||||||
|
"HTTP/1.1 {status} Scripted\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{reply}",
|
||||||
|
reply.len()
|
||||||
|
);
|
||||||
|
let _ = stream.write_all(response.as_bytes());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run(state: &Path, responder: &Responder, ticks: &str, cap: &str) -> Output {
|
||||||
|
run_with(state, responder, ticks, cap, &[])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run_with(state: &Path, responder: &Responder, ticks: &str, cap: &str, extra: &[&str]) -> Output {
|
||||||
|
let url = responder.url();
|
||||||
|
let mut arguments = vec![
|
||||||
|
"run",
|
||||||
|
"--state",
|
||||||
|
state.to_str().unwrap(),
|
||||||
|
"--ticks",
|
||||||
|
ticks,
|
||||||
|
"--token-cap",
|
||||||
|
cap,
|
||||||
|
"--tick-span-minutes",
|
||||||
|
"60",
|
||||||
|
"--model",
|
||||||
|
"local/scripted",
|
||||||
|
"--base-url",
|
||||||
|
&url,
|
||||||
|
];
|
||||||
|
arguments.extend_from_slice(extra);
|
||||||
|
verse(&arguments)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn binary_run_takes_depth_and_band_flags_and_reports_by_node() {
|
||||||
|
let state = tempfile::tempdir().unwrap();
|
||||||
|
assert!(genesis(state.path()).status.success());
|
||||||
|
let responder = Responder::start();
|
||||||
|
let output = run_with(
|
||||||
|
state.path(),
|
||||||
|
&responder,
|
||||||
|
"1",
|
||||||
|
"1000000",
|
||||||
|
&["--depth", "8", "--band", "0=60", "--band", "1=240"],
|
||||||
|
);
|
||||||
|
assert!(output.status.success(), "{}", stderr(&output));
|
||||||
|
let text = stdout(&output);
|
||||||
|
// Opened to every institution, each faction is its own node; with no focus
|
||||||
|
// each sits at the last band's index.
|
||||||
|
for faction in ["Adrasteia", "Brannoch"] {
|
||||||
|
assert!(text.contains(&format!(" node {faction} (distance 1): ")), "{text}");
|
||||||
|
}
|
||||||
|
assert!(text.contains("tick 0 closed: 2 cells, 2 acts, 0 refused\n"), "{text}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn binary_run_prints_acts_and_spend() {
|
||||||
|
let state = tempfile::tempdir().unwrap();
|
||||||
|
let made = genesis(state.path());
|
||||||
|
assert!(made.status.success(), "{}", stderr(&made));
|
||||||
|
let made = stdout(&made);
|
||||||
|
assert!(made.contains("factions 2\n") && made.contains("phase Active\n"), "{made}");
|
||||||
|
assert!(state.path().join("world.cc").is_file());
|
||||||
|
|
||||||
|
let responder = Responder::start();
|
||||||
|
let output = run(state.path(), &responder, "2", "1000000");
|
||||||
|
assert!(output.status.success(), "{}", stderr(&output));
|
||||||
|
let text = stdout(&output);
|
||||||
|
|
||||||
|
// Two ticks, each with both factions named by verb, and the spend as it
|
||||||
|
// accrues against the cap.
|
||||||
|
assert!(text.starts_with("run 1: 2 ticks of 60 minutes, cap 1000000 tokens"), "{text}");
|
||||||
|
for tick in 0..2u64 {
|
||||||
|
let spent = PER_CALL * 2 * (tick + 1);
|
||||||
|
assert!(
|
||||||
|
text.contains(&format!("tick {tick} closed: 2 cells, 2 acts, 0 refused\n")),
|
||||||
|
"{text}"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
text.contains(&format!(
|
||||||
|
" tokens: {} this tick, {spent} spent, {} remaining\n",
|
||||||
|
PER_CALL * 2,
|
||||||
|
1_000_000 - spent
|
||||||
|
)),
|
||||||
|
"{text}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for faction in ["Adrasteia", "Brannoch"] {
|
||||||
|
assert_eq!(
|
||||||
|
text.matches(&format!(" {faction} speak [")).count(),
|
||||||
|
2,
|
||||||
|
"{text}"
|
||||||
|
);
|
||||||
|
assert!(text.contains(&format!("says \"{faction} holds the line.\"")), "{text}");
|
||||||
|
}
|
||||||
|
assert!(text.ends_with("status: Completed; 2 of 2 ticks closed\n"), "{text}");
|
||||||
|
assert_eq!(responder.served.load(Ordering::SeqCst), 4);
|
||||||
|
|
||||||
|
// The state root holds each store the run wrote.
|
||||||
|
for file in ["world.cc", "controller-work.cc", "runs.cc", "calls.cc"] {
|
||||||
|
assert!(state.path().join(file).is_file(), "{file} was not written");
|
||||||
|
}
|
||||||
|
|
||||||
|
// A second run is the next in the world and carries on from its clock.
|
||||||
|
let again = run(state.path(), &responder, "1", "1000000");
|
||||||
|
assert!(again.status.success(), "{}", stderr(&again));
|
||||||
|
let text = stdout(&again);
|
||||||
|
assert!(text.starts_with("run 2: 1 ticks of 60 minutes"), "{text}");
|
||||||
|
assert!(text.contains("tick 2 closed: 2 cells, 2 acts, 0 refused\n"), "{text}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_cap_the_first_call_could_pass_ends_the_run_with_nothing_spent() {
|
||||||
|
let state = tempfile::tempdir().unwrap();
|
||||||
|
assert!(genesis(state.path()).status.success());
|
||||||
|
let responder = Responder::start();
|
||||||
|
let output = run(state.path(), &responder, "3", "1000");
|
||||||
|
assert!(output.status.success(), "{}", stderr(&output));
|
||||||
|
let text = stdout(&output);
|
||||||
|
assert!(text.contains("tick 0 open: "), "{text}");
|
||||||
|
assert!(text.contains("tokens: 0 this tick, 0 spent, 1000 remaining"), "{text}");
|
||||||
|
assert!(text.ends_with("status: BudgetExhausted; 0 of 3 ticks closed\n"), "{text}");
|
||||||
|
assert_eq!(responder.served.load(Ordering::SeqCst), 0, "no call was made");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_run_that_fails_says_so_and_exits_nonzero() {
|
||||||
|
let state = tempfile::tempdir().unwrap();
|
||||||
|
assert!(genesis(state.path()).status.success());
|
||||||
|
let responder = Responder::refusing(500);
|
||||||
|
let output = run(state.path(), &responder, "2", "1000000");
|
||||||
|
assert!(!output.status.success());
|
||||||
|
let text = stdout(&output);
|
||||||
|
assert!(text.contains("tick 0 open: "), "{text}");
|
||||||
|
assert!(
|
||||||
|
text.ends_with("status: Failed (inference_recovery_required); 0 of 2 ticks closed\n"),
|
||||||
|
"{text}"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
responder.served.load(Ordering::SeqCst),
|
||||||
|
1,
|
||||||
|
"the run stopped at the first refusal"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_command_refuses_what_it_cannot_run_and_never_echoes_a_value() {
|
||||||
|
let state = tempfile::tempdir().unwrap();
|
||||||
|
let responder = Responder::start();
|
||||||
|
|
||||||
|
// No world yet.
|
||||||
|
let output = run(state.path(), &responder, "1", "1000");
|
||||||
|
assert!(!output.status.success());
|
||||||
|
assert!(stderr(&output).contains("run genesis first"), "{}", stderr(&output));
|
||||||
|
|
||||||
|
assert!(genesis(state.path()).status.success());
|
||||||
|
// A second genesis does not overwrite the first.
|
||||||
|
assert!(!genesis(state.path()).status.success());
|
||||||
|
|
||||||
|
let secret = "sk-not-a-real-key-0000";
|
||||||
|
let key = state.path().join(secret);
|
||||||
|
let cases: [(Vec<&str>, &str); 11] = [
|
||||||
|
(vec![], "usage"),
|
||||||
|
(vec!["fly"], "unknown command"),
|
||||||
|
(
|
||||||
|
vec!["run", "--state", state.path().to_str().unwrap(), "--ticks", "0"],
|
||||||
|
"--token-cap is required",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
vec![
|
||||||
|
"run", "--state", state.path().to_str().unwrap(), "--ticks", "many",
|
||||||
|
"--token-cap", "1", "--tick-span-minutes", "60", "--model", "local/x",
|
||||||
|
"--base-url", "http://127.0.0.1:1",
|
||||||
|
],
|
||||||
|
"--ticks is not a positive integer",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
vec![
|
||||||
|
"run", "--state", state.path().to_str().unwrap(), "--ticks", "0",
|
||||||
|
"--token-cap", "1", "--tick-span-minutes", "60", "--model", "local/x",
|
||||||
|
"--base-url", "http://127.0.0.1:1",
|
||||||
|
],
|
||||||
|
"--ticks is not a positive integer",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
vec![
|
||||||
|
"run", "--state", state.path().to_str().unwrap(), "--ticks", "1",
|
||||||
|
"--token-cap", "0", "--tick-span-minutes", "60", "--model", "local/x",
|
||||||
|
"--base-url", "http://127.0.0.1:1",
|
||||||
|
],
|
||||||
|
"--token-cap is not a positive integer",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
vec![
|
||||||
|
"run", "--state", state.path().to_str().unwrap(), "--ticks", "1",
|
||||||
|
"--token-cap", "1", "--tick-span-minutes", "60", "--model", "gpt-4",
|
||||||
|
"--base-url", "http://127.0.0.1:1",
|
||||||
|
],
|
||||||
|
"--model names no inference lane",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
// A hosted model needs its key file; a missing one is named by flag.
|
||||||
|
vec![
|
||||||
|
"run", "--state", state.path().to_str().unwrap(), "--ticks", "1",
|
||||||
|
"--token-cap", "1", "--tick-span-minutes", "60", "--model", "hosted/x",
|
||||||
|
"--base-url", "https://api.example.test", "--key-file", key.to_str().unwrap(),
|
||||||
|
],
|
||||||
|
"--key-file is unreadable",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
vec![
|
||||||
|
"run", "--state", state.path().to_str().unwrap(), "--ticks", "1",
|
||||||
|
"--token-cap", "1", "--tick-span-minutes", "60", "--model", "local/x",
|
||||||
|
"--base-url", "http://127.0.0.1:1", "--key-file", key.to_str().unwrap(),
|
||||||
|
],
|
||||||
|
"a local model takes no --key-file",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
vec![
|
||||||
|
"run", "--state", state.path().to_str().unwrap(), "--ticks", "1",
|
||||||
|
"--token-cap", "1", "--tick-span-minutes", "60", "--model", "local/x",
|
||||||
|
"--base-url", "http://127.0.0.1:1", "--band", "1=60",
|
||||||
|
],
|
||||||
|
"--band must name distances 0, 1, 2",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
vec![
|
||||||
|
"run", "--state", state.path().to_str().unwrap(), "--ticks", "1",
|
||||||
|
"--token-cap", "1", "--tick-span-minutes", "60", "--model", "local/x",
|
||||||
|
"--base-url", "http://127.0.0.1:1", "--depth", "0",
|
||||||
|
],
|
||||||
|
"--depth is not a positive integer",
|
||||||
|
),
|
||||||
|
];
|
||||||
|
for (arguments, expected) in cases {
|
||||||
|
let output = verse(&arguments);
|
||||||
|
assert!(!output.status.success(), "{arguments:?} succeeded");
|
||||||
|
let error = stderr(&output);
|
||||||
|
assert!(error.contains(expected), "{arguments:?}: {error}");
|
||||||
|
assert!(!error.contains(secret), "{arguments:?} echoed a path: {error}");
|
||||||
|
assert!(!error.contains("many"), "{arguments:?} echoed a value: {error}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_non_loopback_local_endpoint_is_refused_without_echoing_it() {
|
||||||
|
let state = tempfile::tempdir().unwrap();
|
||||||
|
assert!(genesis(state.path()).status.success());
|
||||||
|
let output = verse(&[
|
||||||
|
"run",
|
||||||
|
"--state",
|
||||||
|
state.path().to_str().unwrap(),
|
||||||
|
"--ticks",
|
||||||
|
"1",
|
||||||
|
"--token-cap",
|
||||||
|
"1000",
|
||||||
|
"--tick-span-minutes",
|
||||||
|
"60",
|
||||||
|
"--model",
|
||||||
|
"local/x",
|
||||||
|
"--base-url",
|
||||||
|
"http://10.77.0.99:4242",
|
||||||
|
]);
|
||||||
|
assert!(!output.status.success());
|
||||||
|
let error = stderr(&output);
|
||||||
|
assert!(error.contains("--base-url"), "{error}");
|
||||||
|
assert!(!error.contains("10.77.0.99"), "the endpoint was echoed: {error}");
|
||||||
|
// The lane failed before any run was claimed.
|
||||||
|
assert!(!stdout(&output).contains("run 1"), "{}", stdout(&output));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A start refused after its claim ends the claimed record Failed, so the run
|
||||||
|
/// binds nothing. Reached from the command by removing the run records while
|
||||||
|
/// the call ledger still holds run 1 under another cap.
|
||||||
|
#[test]
|
||||||
|
fn a_start_the_ledger_refuses_ends_its_claimed_record_failed() {
|
||||||
|
let parent = tempfile::tempdir().unwrap();
|
||||||
|
let state = parent.path().join("state");
|
||||||
|
std::fs::create_dir_all(&state).unwrap();
|
||||||
|
assert!(genesis(&state).status.success());
|
||||||
|
let responder = Responder::start();
|
||||||
|
let first = run(&state, &responder, "1", "1000000");
|
||||||
|
assert!(first.status.success(), "{}", stderr(&first));
|
||||||
|
std::fs::remove_file(state.join("runs.cc")).unwrap();
|
||||||
|
|
||||||
|
let refused = run(&state, &responder, "1", "500000");
|
||||||
|
assert!(!refused.status.success());
|
||||||
|
|
||||||
|
let world = {
|
||||||
|
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||||
|
.enable_all()
|
||||||
|
.build()
|
||||||
|
.unwrap();
|
||||||
|
let _entered = runtime.enter();
|
||||||
|
let (mailbox, task) = ghostlight::WorldMailbox::open(state.join("world.cc")).unwrap();
|
||||||
|
let world = runtime.block_on(mailbox.snapshot()).unwrap().world_id;
|
||||||
|
drop(mailbox);
|
||||||
|
runtime.block_on(task).unwrap();
|
||||||
|
world
|
||||||
|
};
|
||||||
|
let runs = ghostlight::VerseRunStore::open(state.join("runs.cc"))
|
||||||
|
.unwrap()
|
||||||
|
.runs(world)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(runs.len(), 1);
|
||||||
|
assert_eq!(
|
||||||
|
runs[0].status,
|
||||||
|
ghostlight::RunStatus::Failed {
|
||||||
|
reason: "start_refused".into()
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A store that cannot open names the flag and the fault, never the path.
|
||||||
|
#[test]
|
||||||
|
fn a_store_that_cannot_open_never_echoes_the_state_path() {
|
||||||
|
let responder = Responder::start();
|
||||||
|
for file in ["world.cc", "controller-work.cc"] {
|
||||||
|
for held in [false, true] {
|
||||||
|
let parent = tempfile::tempdir().unwrap();
|
||||||
|
let state = parent.path().join("distinctivestatename");
|
||||||
|
std::fs::create_dir_all(&state).unwrap();
|
||||||
|
assert!(genesis(&state).status.success());
|
||||||
|
let first = run(&state, &responder, "1", "1000000");
|
||||||
|
assert!(first.status.success(), "{}", stderr(&first));
|
||||||
|
|
||||||
|
let target = state.join(file);
|
||||||
|
let _guard: Box<dyn std::any::Any> = if !held {
|
||||||
|
std::fs::write(&target, b"not a database").unwrap();
|
||||||
|
Box::new(())
|
||||||
|
} else if file == "world.cc" {
|
||||||
|
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||||
|
.enable_all()
|
||||||
|
.build()
|
||||||
|
.unwrap();
|
||||||
|
let entered = runtime.enter();
|
||||||
|
let opened = ghostlight::WorldMailbox::open(&target).unwrap();
|
||||||
|
drop(entered);
|
||||||
|
Box::new((runtime, opened))
|
||||||
|
} else {
|
||||||
|
Box::new(ghostlight::open_controller_work(&target).unwrap())
|
||||||
|
};
|
||||||
|
|
||||||
|
let output = run(&state, &responder, "1", "1000000");
|
||||||
|
assert!(!output.status.success(), "{file} held={held}");
|
||||||
|
let error = stderr(&output);
|
||||||
|
assert!(error.contains("--state"), "{file} held={held}: {error}");
|
||||||
|
assert!(
|
||||||
|
!error.contains("distinctivestatename"),
|
||||||
|
"{file} held={held} echoed the path: {error}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -7,11 +7,12 @@ license.workspace = true
|
||||||
[dependencies]
|
[dependencies]
|
||||||
async-trait.workspace = true
|
async-trait.workspace = true
|
||||||
chrono.workspace = true
|
chrono.workspace = true
|
||||||
codex-connector.workspace = true
|
model-connector.workspace = true
|
||||||
cultcache-rs.workspace = true
|
cultcache-rs.workspace = true
|
||||||
ghostlight-persona-projection = { path = "../ghostlight-persona-projection" }
|
ghostlight-persona-projection = { path = "../ghostlight-persona-projection" }
|
||||||
reqwest.workspace = true
|
reqwest.workspace = true
|
||||||
rmp-serde.workspace = true
|
rmp-serde.workspace = true
|
||||||
|
rmpv = "1.3"
|
||||||
serde.workspace = true
|
serde.workspace = true
|
||||||
serde_bytes = "0.11"
|
serde_bytes = "0.11"
|
||||||
serde_json.workspace = true
|
serde_json.workspace = true
|
||||||
|
|
@ -19,8 +20,15 @@ sha2.workspace = true
|
||||||
thiserror.workspace = true
|
thiserror.workspace = true
|
||||||
tokio.workspace = true
|
tokio.workspace = true
|
||||||
tracing.workspace = true
|
tracing.workspace = true
|
||||||
|
unicode-normalization = "0.1.25"
|
||||||
|
unicode-properties = "0.1.4"
|
||||||
uuid.workspace = true
|
uuid.workspace = true
|
||||||
zeroize.workspace = true
|
zeroize.workspace = true
|
||||||
|
|
||||||
|
[features]
|
||||||
|
# Exposes `open_local_port_with_timeout` to a consumer's tests. Production
|
||||||
|
# builds never enable it.
|
||||||
|
test-support = []
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
tempfile = "3"
|
tempfile = "3"
|
||||||
|
|
|
||||||
|
|
@ -928,6 +928,14 @@ fn lower(
|
||||||
source: patch::PressureSourceRef::Subject(patch::Ref::Existing(actor)),
|
source: patch::PressureSourceRef::Subject(patch::Ref::Existing(actor)),
|
||||||
target: subject(0)?,
|
target: subject(0)?,
|
||||||
},
|
},
|
||||||
|
// The regarded subject is the actor, so a proposer cannot aim one
|
||||||
|
// person's grudge at a third party; the delta is the entry's.
|
||||||
|
ComponentOpKind::AdjustAttitude { delta, decay } => patch::ComponentOp::AdjustAttitude {
|
||||||
|
holder: subject(0)?,
|
||||||
|
toward: patch::Ref::Existing(actor),
|
||||||
|
delta: *delta,
|
||||||
|
decay: *decay,
|
||||||
|
},
|
||||||
ComponentOpKind::Relocate => patch::ComponentOp::Relocate {
|
ComponentOpKind::Relocate => patch::ComponentOp::Relocate {
|
||||||
subject: subject(0)?,
|
subject: subject(0)?,
|
||||||
via: edge(1)?,
|
via: edge(1)?,
|
||||||
|
|
@ -2834,7 +2842,8 @@ mod tests {
|
||||||
| ComponentOpKind::CreateCommitment { .. }
|
| ComponentOpKind::CreateCommitment { .. }
|
||||||
| ComponentOpKind::AdvancePressure { .. }
|
| ComponentOpKind::AdvancePressure { .. }
|
||||||
| ComponentOpKind::ReducePressure { .. }
|
| ComponentOpKind::ReducePressure { .. }
|
||||||
| ComponentOpKind::ResolvePressure => false,
|
| ComponentOpKind::ResolvePressure
|
||||||
|
| ComponentOpKind::AdjustAttitude { .. } => false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
297
crates/ghostlight/src/aetheria.rs
Normal file
297
crates/ghostlight/src/aetheria.rs
Normal file
|
|
@ -0,0 +1,297 @@
|
||||||
|
//! Aetheria's catalog file, read once into the two things Ghostlight takes from
|
||||||
|
//! it: the verse grammar, as a `GrammarBinding`, and the factions, as records
|
||||||
|
//! keyed for import.
|
||||||
|
//!
|
||||||
|
//! The catalog is Aetheria's: this reader opens it read-only and never writes
|
||||||
|
//! it, and it ignores every schema it does not mirror. The mirrors below decode
|
||||||
|
//! `aetheria.verse_grammar` v1, `aetheria.verse_verb` v1 and `aetheria.faction`
|
||||||
|
//! v1 by integer key: a MessagePack-keyed object is an array indexed by key,
|
||||||
|
//! nil in the gaps, so a field Aetheria adds later at a higher key is ignored
|
||||||
|
//! and a field it drops is an error naming the record and the key. A record
|
||||||
|
//! that does not decode, an enum value outside the mirror and a verb that
|
||||||
|
//! breaks the grammar's name or role rules are errors, never skipped rows.
|
||||||
|
|
||||||
|
use crate::ImportKey;
|
||||||
|
use crate::grammar::{
|
||||||
|
GrammarBinding, GrammarError, GrammarReferentKind, GrammarRole, GrammarVerb, RenderPath,
|
||||||
|
};
|
||||||
|
use cultcache_rs::SingleFileMessagePackBackingStore;
|
||||||
|
use rmpv::Value;
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
const GRAMMAR_SCHEMA: &str = "aetheria.verse_grammar";
|
||||||
|
const VERB_SCHEMA: &str = "aetheria.verse_verb";
|
||||||
|
const FACTION_SCHEMA: &str = "aetheria.faction";
|
||||||
|
|
||||||
|
const VERB_NAME_MAX: usize = 48;
|
||||||
|
const ROLE_NAME_MAX: usize = 32;
|
||||||
|
/// The invoking subject, never a role.
|
||||||
|
const ACTOR_ROLE: &str = "actor";
|
||||||
|
|
||||||
|
/// What Ghostlight takes from Aetheria's catalog.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub struct AetheriaCatalog {
|
||||||
|
pub grammar: GrammarBinding,
|
||||||
|
/// In record-key order.
|
||||||
|
pub factions: Vec<AetheriaFaction>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One `aetheria.faction` record. `allegiance` is carried and read by no
|
||||||
|
/// consumer yet.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub struct AetheriaFaction {
|
||||||
|
pub key: ImportKey,
|
||||||
|
pub name: String,
|
||||||
|
pub short_name: String,
|
||||||
|
pub description: String,
|
||||||
|
pub allegiance: BTreeMap<ImportKey, f32>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Which of the grammar's name or role rules a verb broke.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
|
||||||
|
pub enum VerbRule {
|
||||||
|
#[error("verb name is not canonical")]
|
||||||
|
Name,
|
||||||
|
#[error("role name is not canonical")]
|
||||||
|
RoleName,
|
||||||
|
#[error("role name is reserved for the invoking subject")]
|
||||||
|
ReservedRole,
|
||||||
|
#[error("role name is declared twice")]
|
||||||
|
DuplicateRole,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why a catalog could not be read. Records are named by record key and fields
|
||||||
|
/// by integer key; no error carries a value the catalog held.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
|
||||||
|
pub enum CatalogReadError {
|
||||||
|
#[error("the catalog file cannot be read")]
|
||||||
|
Unreadable,
|
||||||
|
#[error("the catalog holds no aetheria.verse_grammar global")]
|
||||||
|
NoGrammar,
|
||||||
|
#[error("the catalog holds more than one aetheria.verse_grammar record")]
|
||||||
|
MultipleGrammars,
|
||||||
|
#[error("record {record:?} field {field} is missing or not the mirrored type")]
|
||||||
|
MalformedRecord { record: String, field: u8 },
|
||||||
|
#[error("record {record:?} field {field} is not a canonical import key")]
|
||||||
|
NonCanonicalKey { record: String, field: u8 },
|
||||||
|
#[error("record {record:?} is a second aetheria.faction under one record key")]
|
||||||
|
DuplicateFaction { record: String },
|
||||||
|
#[error("record {record:?} field {field} is not a known render path")]
|
||||||
|
UnknownRenderPath { record: String, field: u8 },
|
||||||
|
#[error("record {record:?} field {field} is not a known referent kind")]
|
||||||
|
UnknownReferentKind { record: String, field: u8 },
|
||||||
|
#[error("verb record {record:?} breaks a grammar rule: {rule}")]
|
||||||
|
InvalidVerb { record: String, rule: VerbRule },
|
||||||
|
#[error("the verbs do not bind a grammar: {0}")]
|
||||||
|
Grammar(#[from] GrammarError),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads the catalog at `path` without writing it. An absent file is
|
||||||
|
/// `Unreadable`, not an empty catalog.
|
||||||
|
pub fn read_aetheria_catalog(path: impl AsRef<Path>) -> Result<AetheriaCatalog, CatalogReadError> {
|
||||||
|
let path = path.as_ref();
|
||||||
|
std::fs::metadata(path).map_err(|_| CatalogReadError::Unreadable)?;
|
||||||
|
let mut rows = SingleFileMessagePackBackingStore::new(path)
|
||||||
|
.pull_all_read_only_snapshot()
|
||||||
|
.map_err(|_| CatalogReadError::Unreadable)?;
|
||||||
|
rows.sort_by(|a, b| a.key.cmp(&b.key));
|
||||||
|
|
||||||
|
let mut revision = None;
|
||||||
|
let mut verbs = Vec::new();
|
||||||
|
let mut factions = Vec::new();
|
||||||
|
for row in &rows {
|
||||||
|
match row.r#type.as_str() {
|
||||||
|
GRAMMAR_SCHEMA => {
|
||||||
|
if revision.is_some() {
|
||||||
|
return Err(CatalogReadError::MultipleGrammars);
|
||||||
|
}
|
||||||
|
let cells = Cells::of(&row.key, &row.payload)?;
|
||||||
|
revision = Some(u32::try_from(cells.int(1)?).map_err(|_| cells.malformed(1))?);
|
||||||
|
}
|
||||||
|
VERB_SCHEMA => verbs.push(read_verb(&Cells::of(&row.key, &row.payload)?)?),
|
||||||
|
FACTION_SCHEMA => {
|
||||||
|
let faction = read_faction(&row.key, &Cells::of(&row.key, &row.payload)?)?;
|
||||||
|
if factions
|
||||||
|
.last()
|
||||||
|
.is_some_and(|seen: &AetheriaFaction| seen.key == faction.key)
|
||||||
|
{
|
||||||
|
return Err(CatalogReadError::DuplicateFaction {
|
||||||
|
record: row.key.clone(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
factions.push(faction);
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let revision = revision.ok_or(CatalogReadError::NoGrammar)?;
|
||||||
|
Ok(AetheriaCatalog {
|
||||||
|
grammar: GrammarBinding::new(GRAMMAR_SCHEMA, revision, verbs)?,
|
||||||
|
factions,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A record's payload: the positional array of its keyed fields.
|
||||||
|
struct Cells<'a> {
|
||||||
|
record: &'a str,
|
||||||
|
cells: Vec<Value>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Cells<'a> {
|
||||||
|
fn of(record: &'a str, payload: &[u8]) -> Result<Self, CatalogReadError> {
|
||||||
|
let mut payload = payload;
|
||||||
|
match rmpv::decode::read_value(&mut payload) {
|
||||||
|
Ok(Value::Array(cells)) => Ok(Self { record, cells }),
|
||||||
|
_ => Err(CatalogReadError::MalformedRecord {
|
||||||
|
record: record.to_owned(),
|
||||||
|
field: 0,
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn malformed(&self, field: u8) -> CatalogReadError {
|
||||||
|
CatalogReadError::MalformedRecord {
|
||||||
|
record: self.record.to_owned(),
|
||||||
|
field,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn non_canonical(&self, field: u8) -> CatalogReadError {
|
||||||
|
CatalogReadError::NonCanonicalKey {
|
||||||
|
record: self.record.to_owned(),
|
||||||
|
field,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cell(&self, field: u8) -> Result<&Value, CatalogReadError> {
|
||||||
|
self.cells
|
||||||
|
.get(usize::from(field))
|
||||||
|
.ok_or_else(|| self.malformed(field))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn int(&self, field: u8) -> Result<i64, CatalogReadError> {
|
||||||
|
self.cell(field)?
|
||||||
|
.as_i64()
|
||||||
|
.ok_or_else(|| self.malformed(field))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn text(&self, field: u8) -> Result<String, CatalogReadError> {
|
||||||
|
self.cell(field)?
|
||||||
|
.as_str()
|
||||||
|
.map(str::to_owned)
|
||||||
|
.ok_or_else(|| self.malformed(field))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A string Aetheria may leave null; null reads as empty.
|
||||||
|
fn text_or_empty(&self, field: u8) -> Result<String, CatalogReadError> {
|
||||||
|
match self.cell(field)? {
|
||||||
|
Value::Nil => Ok(String::new()),
|
||||||
|
Value::String(text) => text
|
||||||
|
.as_str()
|
||||||
|
.map(str::to_owned)
|
||||||
|
.ok_or_else(|| self.malformed(field)),
|
||||||
|
_ => Err(self.malformed(field)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn array(&self, field: u8) -> Result<&Vec<Value>, CatalogReadError> {
|
||||||
|
self.cell(field)?
|
||||||
|
.as_array()
|
||||||
|
.ok_or_else(|| self.malformed(field))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_verb(cells: &Cells) -> Result<(String, GrammarVerb), CatalogReadError> {
|
||||||
|
let invalid = |rule| CatalogReadError::InvalidVerb {
|
||||||
|
record: cells.record.to_owned(),
|
||||||
|
rule,
|
||||||
|
};
|
||||||
|
let name = cells.text(1)?;
|
||||||
|
if !canonical_name(&name, VERB_NAME_MAX) {
|
||||||
|
return Err(invalid(VerbRule::Name));
|
||||||
|
}
|
||||||
|
let render_path = match cells.int(2)? {
|
||||||
|
1 => RenderPath::ShipAction,
|
||||||
|
2 => RenderPath::Conversation,
|
||||||
|
_ => {
|
||||||
|
return Err(CatalogReadError::UnknownRenderPath {
|
||||||
|
record: cells.record.to_owned(),
|
||||||
|
field: 2,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let mut roles: Vec<GrammarRole> = Vec::new();
|
||||||
|
for role in cells.array(3)? {
|
||||||
|
let role = Cells {
|
||||||
|
record: cells.record,
|
||||||
|
cells: role.as_array().cloned().ok_or_else(|| cells.malformed(3))?,
|
||||||
|
};
|
||||||
|
let role_name = role.text(1).map_err(|_| cells.malformed(3))?;
|
||||||
|
if !canonical_name(&role_name, ROLE_NAME_MAX) {
|
||||||
|
return Err(invalid(VerbRule::RoleName));
|
||||||
|
}
|
||||||
|
if role_name == ACTOR_ROLE {
|
||||||
|
return Err(invalid(VerbRule::ReservedRole));
|
||||||
|
}
|
||||||
|
if roles.iter().any(|seen| seen.role == role_name) {
|
||||||
|
return Err(invalid(VerbRule::DuplicateRole));
|
||||||
|
}
|
||||||
|
let referent = match role.int(2).map_err(|_| cells.malformed(3))? {
|
||||||
|
1 => GrammarReferentKind::Person,
|
||||||
|
2 => GrammarReferentKind::Faction,
|
||||||
|
3 => GrammarReferentKind::Population,
|
||||||
|
4 => GrammarReferentKind::Place,
|
||||||
|
5 => GrammarReferentKind::Cargo,
|
||||||
|
_ => {
|
||||||
|
return Err(CatalogReadError::UnknownReferentKind {
|
||||||
|
record: cells.record.to_owned(),
|
||||||
|
field: 3,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
roles.push(GrammarRole {
|
||||||
|
role: role_name,
|
||||||
|
referent,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok((name, GrammarVerb { render_path, roles }))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A lower-case letter, then lower-case letters, digits and underscores.
|
||||||
|
fn canonical_name(name: &str, max_len: usize) -> bool {
|
||||||
|
let mut chars = name.chars();
|
||||||
|
name.len() <= max_len
|
||||||
|
&& chars.next().is_some_and(|c| c.is_ascii_lowercase())
|
||||||
|
&& chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_faction(key: &str, cells: &Cells) -> Result<AetheriaFaction, CatalogReadError> {
|
||||||
|
let own = ImportKey::new(FACTION_SCHEMA, key);
|
||||||
|
if !own.is_canonical() {
|
||||||
|
return Err(cells.non_canonical(0));
|
||||||
|
}
|
||||||
|
let Some(allegiance) = cells.cell(12)?.as_map() else {
|
||||||
|
return Err(cells.malformed(12));
|
||||||
|
};
|
||||||
|
let mut standing = BTreeMap::new();
|
||||||
|
for (other, weight) in allegiance {
|
||||||
|
let other = other.as_str().ok_or_else(|| cells.malformed(12))?;
|
||||||
|
let weight = weight.as_f64().ok_or_else(|| cells.malformed(12))?;
|
||||||
|
let other = ImportKey::new(FACTION_SCHEMA, other);
|
||||||
|
if !other.is_canonical() {
|
||||||
|
return Err(cells.non_canonical(12));
|
||||||
|
}
|
||||||
|
standing.insert(other, weight as f32);
|
||||||
|
}
|
||||||
|
Ok(AetheriaFaction {
|
||||||
|
key: own,
|
||||||
|
name: cells.text(1)?,
|
||||||
|
short_name: cells.text_or_empty(2)?,
|
||||||
|
description: cells.text_or_empty(3)?,
|
||||||
|
allegiance: standing,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests;
|
||||||
589
crates/ghostlight/src/aetheria/tests.rs
Normal file
589
crates/ghostlight/src/aetheria/tests.rs
Normal file
|
|
@ -0,0 +1,589 @@
|
||||||
|
use super::*;
|
||||||
|
use cultcache_rs::{CacheBackingStore, CultCacheEnvelope};
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
|
/// Written by Aetheria's own fixture writer (`VerseGrammarTests.WriteFixture`)
|
||||||
|
/// at Aetheria master 92b82e9a; never edited. See `tests/fixtures/aetheria-verse-catalog.provenance.txt`.
|
||||||
|
const FIXTURE: &str = concat!(
|
||||||
|
env!("CARGO_MANIFEST_DIR"),
|
||||||
|
"/tests/fixtures/aetheria-verse-catalog.cc"
|
||||||
|
);
|
||||||
|
|
||||||
|
fn fixture_rows() -> Vec<CultCacheEnvelope> {
|
||||||
|
SingleFileMessagePackBackingStore::new(FIXTURE)
|
||||||
|
.pull_all_read_only_snapshot()
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn row_of<'a>(rows: &'a mut [CultCacheEnvelope], key: &str) -> &'a mut CultCacheEnvelope {
|
||||||
|
rows.iter_mut().find(|row| row.key == key).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Re-encodes one record's positional payload after `edit`.
|
||||||
|
fn edit(rows: &mut [CultCacheEnvelope], key: &str, change: impl FnOnce(&mut Vec<Value>)) {
|
||||||
|
let row = row_of(rows, key);
|
||||||
|
let Value::Array(mut cells) = rmp_serde::from_slice(&row.payload).unwrap() else {
|
||||||
|
panic!("{key} is not a positional record");
|
||||||
|
};
|
||||||
|
change(&mut cells);
|
||||||
|
row.payload = rmp_serde::to_vec(&Value::Array(cells)).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn catalog_of(rows: &[CultCacheEnvelope]) -> (tempfile::TempDir, std::path::PathBuf) {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let path = dir.path().join("catalog.cc");
|
||||||
|
let mut store = SingleFileMessagePackBackingStore::new(&path);
|
||||||
|
for row in rows {
|
||||||
|
store.push(row).unwrap();
|
||||||
|
}
|
||||||
|
(dir, path)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read(rows: &[CultCacheEnvelope]) -> Result<AetheriaCatalog, CatalogReadError> {
|
||||||
|
let (_dir, path) = catalog_of(rows);
|
||||||
|
read_aetheria_catalog(&path)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn verb(path: RenderPath, roles: &[(&str, GrammarReferentKind)]) -> GrammarVerb {
|
||||||
|
GrammarVerb {
|
||||||
|
render_path: path,
|
||||||
|
roles: roles
|
||||||
|
.iter()
|
||||||
|
.map(|(role, referent)| GrammarRole {
|
||||||
|
role: (*role).into(),
|
||||||
|
referent: *referent,
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What Aetheria's fixture writer authored, spelled out by hand.
|
||||||
|
fn authored_verbs() -> Vec<(String, GrammarVerb)> {
|
||||||
|
vec![
|
||||||
|
(
|
||||||
|
"haul".into(),
|
||||||
|
verb(
|
||||||
|
RenderPath::ShipAction,
|
||||||
|
&[
|
||||||
|
("cargo", GrammarReferentKind::Cargo),
|
||||||
|
("destination", GrammarReferentKind::Place),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"attack".into(),
|
||||||
|
verb(
|
||||||
|
RenderPath::ShipAction,
|
||||||
|
&[("target", GrammarReferentKind::Faction)],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
("speak".into(), verb(RenderPath::Conversation, &[])),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn faction_key(record: &str) -> ImportKey {
|
||||||
|
ImportKey::new("aetheria.faction", record)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reads_the_aetheria_written_fixture() {
|
||||||
|
let catalog = read_aetheria_catalog(FIXTURE).unwrap();
|
||||||
|
|
||||||
|
let identity = catalog.grammar.identity();
|
||||||
|
assert_eq!(identity.schema_id, "aetheria.verse_grammar");
|
||||||
|
assert_eq!(identity.revision, 1);
|
||||||
|
for (kind, expected) in authored_verbs() {
|
||||||
|
assert_eq!(catalog.grammar.verb(&kind), Some(&expected), "{kind}");
|
||||||
|
}
|
||||||
|
assert!(catalog.grammar.verb("mine").is_none());
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
catalog.factions,
|
||||||
|
vec![
|
||||||
|
AetheriaFaction {
|
||||||
|
key: faction_key("faction-adrasteia"),
|
||||||
|
name: "Adrasteia".into(),
|
||||||
|
short_name: "ADR".into(),
|
||||||
|
description: "First.".into(),
|
||||||
|
allegiance: BTreeMap::from([(faction_key("faction-brannoch"), 0.75)]),
|
||||||
|
},
|
||||||
|
AetheriaFaction {
|
||||||
|
key: faction_key("faction-brannoch"),
|
||||||
|
name: "Brannoch".into(),
|
||||||
|
short_name: "BRN".into(),
|
||||||
|
description: "Second.".into(),
|
||||||
|
allegiance: BTreeMap::from([(faction_key("faction-adrasteia"), 0.25)]),
|
||||||
|
},
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn grammar_digest_matches_a_binding_built_by_hand() {
|
||||||
|
let by_hand = GrammarBinding::new("aetheria.verse_grammar", 1, authored_verbs()).unwrap();
|
||||||
|
let read = read_aetheria_catalog(FIXTURE).unwrap().grammar;
|
||||||
|
assert_eq!(read.identity().digest, by_hand.identity().digest);
|
||||||
|
assert_eq!(read, by_hand);
|
||||||
|
|
||||||
|
// The digest follows the verbs: a role the file drops is a different grammar.
|
||||||
|
let mut rows = fixture_rows();
|
||||||
|
edit(&mut rows, "verb-haul", |cells| {
|
||||||
|
cells[3].as_array_mut().unwrap().pop();
|
||||||
|
});
|
||||||
|
assert_ne!(
|
||||||
|
read_catalog_digest(&rows),
|
||||||
|
by_hand.identity().digest,
|
||||||
|
"dropping a role did not move the digest"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_catalog_digest(rows: &[CultCacheEnvelope]) -> String {
|
||||||
|
read(rows).unwrap().grammar.identity().digest
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn refuses_a_catalog_without_a_grammar() {
|
||||||
|
let mut rows = fixture_rows();
|
||||||
|
rows.retain(|row| row.r#type != "aetheria.verse_grammar");
|
||||||
|
assert_eq!(read(&rows), Err(CatalogReadError::NoGrammar));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn refuses_a_second_grammar_record() {
|
||||||
|
let mut rows = fixture_rows();
|
||||||
|
let mut second = rows
|
||||||
|
.iter()
|
||||||
|
.find(|row| row.r#type == "aetheria.verse_grammar")
|
||||||
|
.unwrap()
|
||||||
|
.clone();
|
||||||
|
second.key.push_str("-again");
|
||||||
|
rows.push(second);
|
||||||
|
assert_eq!(read(&rows), Err(CatalogReadError::MultipleGrammars));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn refuses_an_unknown_render_path() {
|
||||||
|
let mut rows = fixture_rows();
|
||||||
|
edit(&mut rows, "verb-haul", |cells| cells[2] = json!(3));
|
||||||
|
let error = read(&rows).unwrap_err();
|
||||||
|
assert_eq!(
|
||||||
|
error,
|
||||||
|
CatalogReadError::UnknownRenderPath {
|
||||||
|
record: "verb-haul".into(),
|
||||||
|
field: 2
|
||||||
|
}
|
||||||
|
);
|
||||||
|
assert!(!error.to_string().contains('3'), "the value was echoed");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn refuses_an_unknown_referent_kind() {
|
||||||
|
let mut rows = fixture_rows();
|
||||||
|
edit(&mut rows, "verb-attack", |cells| {
|
||||||
|
cells[3][0][2] = json!(9);
|
||||||
|
});
|
||||||
|
assert_eq!(
|
||||||
|
read(&rows),
|
||||||
|
Err(CatalogReadError::UnknownReferentKind {
|
||||||
|
record: "verb-attack".into(),
|
||||||
|
field: 3
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_verb_breaking_the_name_or_role_rules_is_refused_by_key() {
|
||||||
|
let broken = |mutate: fn(&mut Vec<Value>)| {
|
||||||
|
let mut rows = fixture_rows();
|
||||||
|
edit(&mut rows, "verb-haul", mutate);
|
||||||
|
read(&rows).unwrap_err()
|
||||||
|
};
|
||||||
|
let invalid = |rule| CatalogReadError::InvalidVerb {
|
||||||
|
record: "verb-haul".into(),
|
||||||
|
rule,
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
broken(|cells| cells[1] = json!("Haul")),
|
||||||
|
invalid(VerbRule::Name)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
broken(|cells| cells[1] = json!("1haul")),
|
||||||
|
invalid(VerbRule::Name)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
broken(|cells| cells[1] = json!("")),
|
||||||
|
invalid(VerbRule::Name)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
broken(|cells| cells[1] = json!("h".repeat(49))),
|
||||||
|
invalid(VerbRule::Name)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
broken(|cells| cells[3][0][1] = json!("Cargo")),
|
||||||
|
invalid(VerbRule::RoleName)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
broken(|cells| cells[3][0][1] = json!("c".repeat(33))),
|
||||||
|
invalid(VerbRule::RoleName)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
broken(|cells| cells[3][0][1] = json!("actor")),
|
||||||
|
invalid(VerbRule::ReservedRole)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
broken(|cells| cells[3][1][1] = json!("cargo")),
|
||||||
|
invalid(VerbRule::DuplicateRole)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_longest_canonical_names_are_admitted() {
|
||||||
|
let mut rows = fixture_rows();
|
||||||
|
edit(&mut rows, "verb-haul", |cells| {
|
||||||
|
cells[1] = json!(format!("h{}9", "_9".repeat(23)));
|
||||||
|
cells[3][0][1] = json!(format!("c{}", "z".repeat(31)));
|
||||||
|
});
|
||||||
|
let catalog = read(&rows).unwrap();
|
||||||
|
assert_eq!(catalog.grammar.identity().revision, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn two_verbs_with_one_name_do_not_bind() {
|
||||||
|
let mut rows = fixture_rows();
|
||||||
|
edit(&mut rows, "verb-haul", |cells| cells[1] = json!("attack"));
|
||||||
|
assert_eq!(
|
||||||
|
read(&rows),
|
||||||
|
Err(CatalogReadError::Grammar(GrammarError::DuplicateVerb))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_record_that_is_not_the_mirrored_shape_is_named_by_key_and_field() {
|
||||||
|
let malformed = |record: &str, field| CatalogReadError::MalformedRecord {
|
||||||
|
record: record.into(),
|
||||||
|
field,
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut rows = fixture_rows();
|
||||||
|
row_of(&mut rows, "faction-brannoch").payload =
|
||||||
|
rmp_serde::to_vec(&json!("not an array")).unwrap();
|
||||||
|
assert_eq!(read(&rows), Err(malformed("faction-brannoch", 0)));
|
||||||
|
|
||||||
|
let mut rows = fixture_rows();
|
||||||
|
edit(&mut rows, "faction-brannoch", |cells| {
|
||||||
|
cells[1] = Value::Null
|
||||||
|
});
|
||||||
|
assert_eq!(read(&rows), Err(malformed("faction-brannoch", 1)));
|
||||||
|
|
||||||
|
let mut rows = fixture_rows();
|
||||||
|
edit(&mut rows, "faction-brannoch", |cells| {
|
||||||
|
cells[12] = json!({"faction-adrasteia": "heavy"});
|
||||||
|
});
|
||||||
|
assert_eq!(read(&rows), Err(malformed("faction-brannoch", 12)));
|
||||||
|
|
||||||
|
let mut rows = fixture_rows();
|
||||||
|
edit(&mut rows, "faction-brannoch", |cells| cells.truncate(12));
|
||||||
|
assert_eq!(read(&rows), Err(malformed("faction-brannoch", 12)));
|
||||||
|
|
||||||
|
let mut rows = fixture_rows();
|
||||||
|
let grammar = rows
|
||||||
|
.iter()
|
||||||
|
.find(|row| row.r#type == "aetheria.verse_grammar")
|
||||||
|
.unwrap()
|
||||||
|
.key
|
||||||
|
.clone();
|
||||||
|
edit(&mut rows, &grammar, |cells| cells[1] = json!(-1));
|
||||||
|
assert_eq!(read(&rows), Err(malformed(&grammar, 1)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fields_aetheria_adds_and_schemas_it_does_not_mirror_are_ignored() {
|
||||||
|
let mut rows = fixture_rows();
|
||||||
|
edit(&mut rows, "verb-speak", |cells| cells.push(json!("later")));
|
||||||
|
edit(&mut rows, "faction-adrasteia", |cells| cells.push(json!(7)));
|
||||||
|
let mut stranger = rows[0].clone();
|
||||||
|
stranger.key = "ship-1".into();
|
||||||
|
stranger.r#type = "aetheria.ship".into();
|
||||||
|
stranger.schema_id = Some("sha256:not-mirrored".into());
|
||||||
|
stranger.payload = vec![0xc1];
|
||||||
|
rows.push(stranger);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
read(&rows).unwrap(),
|
||||||
|
read_aetheria_catalog(FIXTURE).unwrap()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_null_short_name_or_description_reads_as_empty() {
|
||||||
|
let mut rows = fixture_rows();
|
||||||
|
edit(&mut rows, "faction-adrasteia", |cells| {
|
||||||
|
cells[2] = Value::Null;
|
||||||
|
cells[3] = Value::Null;
|
||||||
|
});
|
||||||
|
let catalog = read(&rows).unwrap();
|
||||||
|
assert_eq!(catalog.factions[0].short_name, "");
|
||||||
|
assert_eq!(catalog.factions[0].description, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_absent_file_is_unreadable_not_an_empty_catalog() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
read_aetheria_catalog(dir.path().join("missing.cc")),
|
||||||
|
Err(CatalogReadError::Unreadable)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reading_leaves_the_catalog_and_its_directory_untouched() {
|
||||||
|
let (dir, path) = catalog_of(&fixture_rows());
|
||||||
|
let bytes = std::fs::read(&path).unwrap();
|
||||||
|
let listing = |dir: &std::path::Path| {
|
||||||
|
let mut names: Vec<_> = std::fs::read_dir(dir)
|
||||||
|
.unwrap()
|
||||||
|
.map(|entry| entry.unwrap().file_name())
|
||||||
|
.collect();
|
||||||
|
names.sort();
|
||||||
|
names
|
||||||
|
};
|
||||||
|
let before = listing(dir.path());
|
||||||
|
read_aetheria_catalog(&path).unwrap();
|
||||||
|
read_aetheria_catalog(&path).unwrap();
|
||||||
|
assert_eq!(std::fs::read(&path).unwrap(), bytes);
|
||||||
|
assert_eq!(listing(dir.path()), before, "the reader created a file");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_referent_code_maps_to_its_own_kind() {
|
||||||
|
// The fixture binds only Faction, Cargo and Place; Person and Population
|
||||||
|
// are authored here at the role's integer key, each read back as itself.
|
||||||
|
for (code, expected) in [
|
||||||
|
(1, GrammarReferentKind::Person),
|
||||||
|
(2, GrammarReferentKind::Faction),
|
||||||
|
(3, GrammarReferentKind::Population),
|
||||||
|
(4, GrammarReferentKind::Place),
|
||||||
|
(5, GrammarReferentKind::Cargo),
|
||||||
|
] {
|
||||||
|
let mut rows = fixture_rows();
|
||||||
|
edit(&mut rows, "verb-attack", |cells| {
|
||||||
|
cells[3][0][2] = json!(code)
|
||||||
|
});
|
||||||
|
let catalog = read(&rows).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
catalog.grammar.verb("attack"),
|
||||||
|
Some(&verb(RenderPath::ShipAction, &[("target", expected)])),
|
||||||
|
"code {code}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn faction_with_key(record: &str) -> Vec<CultCacheEnvelope> {
|
||||||
|
let mut rows = fixture_rows();
|
||||||
|
row_of(&mut rows, "faction-brannoch").key = record.into();
|
||||||
|
rows
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_faction_record_key_that_is_not_canonical_text_is_refused_by_key_and_field() {
|
||||||
|
for bad in [
|
||||||
|
"faction-cafe\u{301}",
|
||||||
|
"faction-brannoch ",
|
||||||
|
"faction-\u{202e}brannoch",
|
||||||
|
"",
|
||||||
|
] {
|
||||||
|
assert_eq!(
|
||||||
|
read(&faction_with_key(bad)),
|
||||||
|
Err(CatalogReadError::NonCanonicalKey {
|
||||||
|
record: bad.into(),
|
||||||
|
field: 0
|
||||||
|
}),
|
||||||
|
"{bad:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_allegiance_key_that_is_not_canonical_text_is_refused_by_key_and_field() {
|
||||||
|
for bad in ["faction-cafe\u{301}", "faction-adrasteia ", "\u{202e}"] {
|
||||||
|
let mut rows = fixture_rows();
|
||||||
|
edit(&mut rows, "faction-brannoch", |cells| {
|
||||||
|
cells[12] = json!({ bad: 0.5 });
|
||||||
|
});
|
||||||
|
assert_eq!(
|
||||||
|
read(&rows),
|
||||||
|
Err(CatalogReadError::NonCanonicalKey {
|
||||||
|
record: "faction-brannoch".into(),
|
||||||
|
field: 12
|
||||||
|
}),
|
||||||
|
"{bad:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The fixture's snapshot bytes with the record rows changed by `change`, for
|
||||||
|
/// what the store's own writer will not produce: it keeps one row per record
|
||||||
|
/// key and stores rows in key order.
|
||||||
|
fn spliced_catalog(
|
||||||
|
change: impl FnOnce(&mut Vec<rmpv::Value>),
|
||||||
|
) -> (tempfile::TempDir, std::path::PathBuf) {
|
||||||
|
let bytes = std::fs::read(FIXTURE).unwrap();
|
||||||
|
let rmpv::Value::Array(mut snapshot) = rmpv::decode::read_value(&mut bytes.as_slice()).unwrap()
|
||||||
|
else {
|
||||||
|
panic!("snapshot is not a tuple");
|
||||||
|
};
|
||||||
|
let rmpv::Value::Array(records) = &mut snapshot[2] else {
|
||||||
|
panic!("snapshot holds no records");
|
||||||
|
};
|
||||||
|
change(records);
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let path = dir.path().join("catalog.cc");
|
||||||
|
let mut spliced = Vec::new();
|
||||||
|
rmpv::encode::write_value(&mut spliced, &rmpv::Value::Array(snapshot)).unwrap();
|
||||||
|
std::fs::write(&path, spliced).unwrap();
|
||||||
|
(dir, path)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn two_faction_rows_under_one_record_key_are_refused() {
|
||||||
|
let (_dir, path) = spliced_catalog(|records| {
|
||||||
|
let twin = records
|
||||||
|
.iter()
|
||||||
|
.find(|record| record[0].as_str() == Some("faction-adrasteia"))
|
||||||
|
.unwrap()
|
||||||
|
.clone();
|
||||||
|
records.push(twin);
|
||||||
|
});
|
||||||
|
assert_eq!(
|
||||||
|
read_aetheria_catalog(&path),
|
||||||
|
Err(CatalogReadError::DuplicateFaction {
|
||||||
|
record: "faction-adrasteia".into()
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn factions_are_read_in_record_key_order_whatever_the_file_order() {
|
||||||
|
let (_dir, path) = spliced_catalog(|records| {
|
||||||
|
records.sort_by(|a, b| b[0].as_str().cmp(&a[0].as_str()));
|
||||||
|
assert_eq!(records[0][0].as_str(), Some("verb-speak"));
|
||||||
|
});
|
||||||
|
let names: Vec<_> = read_aetheria_catalog(&path)
|
||||||
|
.unwrap()
|
||||||
|
.factions
|
||||||
|
.into_iter()
|
||||||
|
.map(|faction| faction.name)
|
||||||
|
.collect();
|
||||||
|
assert_eq!(names, ["Adrasteia", "Brannoch"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_allegiance_that_is_not_a_map_is_malformed_not_empty() {
|
||||||
|
for not_a_map in [
|
||||||
|
json!([]),
|
||||||
|
json!(["faction-adrasteia"]),
|
||||||
|
Value::Null,
|
||||||
|
json!(1),
|
||||||
|
] {
|
||||||
|
let mut rows = fixture_rows();
|
||||||
|
let shape = not_a_map.clone();
|
||||||
|
edit(&mut rows, "faction-brannoch", |cells| cells[12] = shape);
|
||||||
|
assert_eq!(
|
||||||
|
read(&rows),
|
||||||
|
Err(CatalogReadError::MalformedRecord {
|
||||||
|
record: "faction-brannoch".into(),
|
||||||
|
field: 12
|
||||||
|
}),
|
||||||
|
"{not_a_map}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Appends cells to a faction as Aetheria's C# CultCache writes a `byte[]`
|
||||||
|
/// (MessagePack bin) and a `DateTime` (MessagePack timestamp, ext -1).
|
||||||
|
#[test]
|
||||||
|
fn bin_and_ext_fields_aetheria_adds_at_higher_keys_are_ignored() {
|
||||||
|
let mut rows = fixture_rows();
|
||||||
|
let row = row_of(&mut rows, "faction-adrasteia");
|
||||||
|
let rmpv::Value::Array(mut cells) =
|
||||||
|
rmpv::decode::read_value(&mut row.payload.as_slice()).unwrap()
|
||||||
|
else {
|
||||||
|
panic!("not positional");
|
||||||
|
};
|
||||||
|
cells.push(rmpv::Value::Binary(vec![1, 0, 7]));
|
||||||
|
cells.push(rmpv::Value::Ext(
|
||||||
|
-1,
|
||||||
|
vec![0, 0, 0, 0, 0x65, 0x1f, 0x2a, 0x80],
|
||||||
|
));
|
||||||
|
let mut payload = Vec::new();
|
||||||
|
rmpv::encode::write_value(&mut payload, &rmpv::Value::Array(cells)).unwrap();
|
||||||
|
row.payload = payload;
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
read(&rows).unwrap(),
|
||||||
|
read_aetheria_catalog(FIXTURE).unwrap()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A faction record re-encoded with `change` applied to its decoded cells, for
|
||||||
|
/// shapes `serde_json` cannot spell: a non-string map key, raw invalid bytes.
|
||||||
|
fn with_cells(key: &str, change: impl FnOnce(&mut Vec<rmpv::Value>)) -> Vec<CultCacheEnvelope> {
|
||||||
|
let mut rows = fixture_rows();
|
||||||
|
let row = row_of(&mut rows, key);
|
||||||
|
let rmpv::Value::Array(mut cells) =
|
||||||
|
rmpv::decode::read_value(&mut row.payload.as_slice()).unwrap()
|
||||||
|
else {
|
||||||
|
panic!("not positional");
|
||||||
|
};
|
||||||
|
change(&mut cells);
|
||||||
|
let mut payload = Vec::new();
|
||||||
|
rmpv::encode::write_value(&mut payload, &rmpv::Value::Array(cells)).unwrap();
|
||||||
|
row.payload = payload;
|
||||||
|
rows
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_allegiance_key_that_is_not_a_string_is_malformed_by_key_and_field() {
|
||||||
|
for key in [
|
||||||
|
rmpv::Value::from(5),
|
||||||
|
rmpv::Value::Nil,
|
||||||
|
rmpv::Value::Binary(b"faction-adrasteia".to_vec()),
|
||||||
|
] {
|
||||||
|
let rows = with_cells("faction-brannoch", |cells| {
|
||||||
|
cells[12] = rmpv::Value::Map(vec![(key, rmpv::Value::F64(0.5))]);
|
||||||
|
});
|
||||||
|
assert_eq!(
|
||||||
|
read(&rows),
|
||||||
|
Err(CatalogReadError::MalformedRecord {
|
||||||
|
record: "faction-brannoch".into(),
|
||||||
|
field: 12
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn text_that_is_not_utf8_is_malformed_by_key_and_field() {
|
||||||
|
// The marker is overwritten in the encoded bytes with an invalid sequence of
|
||||||
|
// the same length, since a decoded string cannot hold one.
|
||||||
|
const MARKER: &str = "ZZZZ";
|
||||||
|
for field in [1usize, 3] {
|
||||||
|
let mut rows = with_cells("faction-brannoch", |cells| {
|
||||||
|
cells[field] = rmpv::Value::from(MARKER);
|
||||||
|
});
|
||||||
|
let payload = &mut row_of(&mut rows, "faction-brannoch").payload;
|
||||||
|
let at = payload
|
||||||
|
.windows(MARKER.len())
|
||||||
|
.position(|window| window == MARKER.as_bytes())
|
||||||
|
.unwrap();
|
||||||
|
payload[at..at + MARKER.len()].copy_from_slice(&[0xff, 0xfe, 0xfd, 0xfc]);
|
||||||
|
assert_eq!(
|
||||||
|
read(&rows),
|
||||||
|
Err(CatalogReadError::MalformedRecord {
|
||||||
|
record: "faction-brannoch".into(),
|
||||||
|
field: field as u8
|
||||||
|
}),
|
||||||
|
"field {field}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
313
crates/ghostlight/src/attitude.rs
Normal file
313
crates/ghostlight/src/attitude.rs
Normal file
|
|
@ -0,0 +1,313 @@
|
||||||
|
//! Attitude: how one subject regards another, as typed kernel state.
|
||||||
|
//!
|
||||||
|
//! The kernel stores *modifiers*, never an opinion. Each is a sourced, bounded,
|
||||||
|
//! possibly fading term (the Crusader Kings shape); `opinion` derives the sum on
|
||||||
|
//! demand and nothing stores it. A modifier points at one subject, or at a
|
||||||
|
//! *trait* (species, faction, a look, a rumour about a person) and a trait
|
||||||
|
//! modifier is prejudice: it applies to a subject only while the holder knows,
|
||||||
|
//! at `Believed` or better, a fact the world declared as evidence that the
|
||||||
|
//! subject carries that trait. A prejudice against outlanders does nothing to a
|
||||||
|
//! stranger the holder has never learned is one.
|
||||||
|
//!
|
||||||
|
//! The reducer is the only writer: `ResolvedOp::AdjustAttitude` and
|
||||||
|
//! `ResolvedOp::DeclareTrait` land here, through patches and affordance
|
||||||
|
//! effects. Persona prose, the narrator, and host code write nothing.
|
||||||
|
|
||||||
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use super::clock::{FictionalMinutes, TickMinutes};
|
||||||
|
use super::patch::{Confidence, Ref};
|
||||||
|
use super::{CommandId, EntityId, SubjectId, WorldState};
|
||||||
|
|
||||||
|
/// The bound on one stored modifier and on a derived opinion: a grudge or a
|
||||||
|
/// fondness saturates here, so no run of insults reaches an unrecoverable
|
||||||
|
/// number and the model-facing schema can say the range.
|
||||||
|
pub(crate) const MAX_ATTITUDE: i16 = 100;
|
||||||
|
|
||||||
|
/// How many of an opinion's causes a view names. The rest are summed in.
|
||||||
|
pub(crate) const OPINION_CAUSES_SHOWN: usize = 3;
|
||||||
|
|
||||||
|
/// World-declared canonical text, kernel-opaque, `[a-z][a-z0-9_]{0,47}`: the
|
||||||
|
/// same shape as an authority kind, because it is the same kind of word.
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||||
|
#[serde(transparent)]
|
||||||
|
pub(crate) struct TraitName(pub(crate) String);
|
||||||
|
|
||||||
|
/// What a modifier regards.
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||||
|
#[serde(tag = "toward", content = "of", rename_all = "snake_case")]
|
||||||
|
pub(crate) enum AttitudeToward {
|
||||||
|
Subject(SubjectId),
|
||||||
|
Trait(TraitName),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why a modifier exists. `Grievance` and `Favor` name the command that did the
|
||||||
|
/// deed, so one act is one row and two acts are two. `Rumour` is a belief the
|
||||||
|
/// holder acted on, and holds only while the holder still knows its fact.
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||||
|
#[serde(tag = "cause", rename_all = "snake_case")]
|
||||||
|
pub(crate) enum AttitudeCause {
|
||||||
|
Prejudice,
|
||||||
|
Grievance { command: CommandId },
|
||||||
|
Favor { command: CommandId },
|
||||||
|
Rumour { fact: EntityId },
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub(crate) struct AttitudeKey {
|
||||||
|
pub(crate) toward: AttitudeToward,
|
||||||
|
pub(crate) cause: AttitudeCause,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Nonzero and within `MAX_ATTITUDE` by construction of every writer. `since`
|
||||||
|
/// is the world clock at the last write; with `decay` it sets how the term
|
||||||
|
/// fades, and with none the term is permanent.
|
||||||
|
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub(crate) struct AttitudeModifier {
|
||||||
|
pub(crate) delta: i16,
|
||||||
|
pub(crate) since: FictionalMinutes,
|
||||||
|
pub(crate) decay: Option<TickMinutes>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The proposal-time twin of [`AttitudeToward`].
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||||
|
#[serde(tag = "toward", content = "of", rename_all = "snake_case")]
|
||||||
|
pub(crate) enum AttitudeTowardRef {
|
||||||
|
Subject(Ref<SubjectId>),
|
||||||
|
Trait(TraitName),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What an authored declaration rests on. A deed is not one of these: a deed
|
||||||
|
/// is `AdjustAttitude`, whose cause the kernel derives from the command.
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||||
|
#[serde(tag = "basis", rename_all = "snake_case")]
|
||||||
|
pub(crate) enum AttitudeBasisRef {
|
||||||
|
Prejudice,
|
||||||
|
Rumour { fact: Ref<EntityId> },
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One cause of a derived opinion, with the delta it contributes right now.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub(crate) struct OpinionCause {
|
||||||
|
pub(crate) toward: AttitudeToward,
|
||||||
|
pub(crate) cause: AttitudeCause,
|
||||||
|
pub(crate) delta: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Holder's regard for one subject: the clamped sum and its causes, strongest
|
||||||
|
/// first. Derived, never stored.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub(crate) struct Opinion {
|
||||||
|
pub(crate) total: i32,
|
||||||
|
pub(crate) causes: Vec<OpinionCause>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A modifier's contribution at `now`: a decaying term fades linearly to zero
|
||||||
|
/// across its period, truncating toward zero.
|
||||||
|
fn effective(modifier: &AttitudeModifier, now: FictionalMinutes) -> i32 {
|
||||||
|
let delta = i64::from(modifier.delta);
|
||||||
|
match modifier.decay {
|
||||||
|
None => delta as i32,
|
||||||
|
Some(period) => {
|
||||||
|
let span = i64::from(period.minutes());
|
||||||
|
let elapsed = i64::try_from(now.since(modifier.since)).unwrap_or(i64::MAX);
|
||||||
|
if elapsed >= span {
|
||||||
|
0
|
||||||
|
} else {
|
||||||
|
(delta * (span - elapsed) / span) as i32
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `holder` holds `fact` at `Believed` or better. A doubted rumour
|
||||||
|
/// moves nobody.
|
||||||
|
fn believes(state: &WorldState, holder: SubjectId, fact: EntityId) -> bool {
|
||||||
|
state
|
||||||
|
.knowledge
|
||||||
|
.get(&holder)
|
||||||
|
.and_then(|held| held.get(&fact))
|
||||||
|
.is_some_and(|entry| entry.confidence >= Confidence::Believed)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the modifier at `key` applies to `subject` for `holder` right now.
|
||||||
|
fn applies(state: &WorldState, holder: SubjectId, key: &AttitudeKey, subject: SubjectId) -> bool {
|
||||||
|
let reaches = match &key.toward {
|
||||||
|
AttitudeToward::Subject(target) => *target == subject,
|
||||||
|
AttitudeToward::Trait(name) => state
|
||||||
|
.traits
|
||||||
|
.get(&subject)
|
||||||
|
.and_then(|carried| carried.get(name))
|
||||||
|
.is_some_and(|evidence| evidence.iter().any(|fact| believes(state, holder, *fact))),
|
||||||
|
};
|
||||||
|
reaches
|
||||||
|
&& match &key.cause {
|
||||||
|
AttitudeCause::Rumour { fact } => believes(state, holder, *fact),
|
||||||
|
_ => true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `holder`'s opinion of `subject`: every applicable modifier, summed and
|
||||||
|
/// clamped. Causes with no remaining weight are dropped; ordered by strength,
|
||||||
|
/// then by key, so the answer is deterministic.
|
||||||
|
pub(crate) fn opinion(state: &WorldState, holder: SubjectId, subject: SubjectId) -> Opinion {
|
||||||
|
let mut causes: Vec<(&AttitudeKey, OpinionCause)> = state
|
||||||
|
.attitudes
|
||||||
|
.get(&holder)
|
||||||
|
.into_iter()
|
||||||
|
.flatten()
|
||||||
|
.filter(|(key, _)| applies(state, holder, key, subject))
|
||||||
|
.map(|(key, modifier)| {
|
||||||
|
(
|
||||||
|
key,
|
||||||
|
OpinionCause {
|
||||||
|
toward: key.toward.clone(),
|
||||||
|
cause: key.cause.clone(),
|
||||||
|
delta: effective(modifier, state.now),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.filter(|(_, cause)| cause.delta != 0)
|
||||||
|
.collect();
|
||||||
|
causes.sort_by(|(left_key, left), (right_key, right)| {
|
||||||
|
right
|
||||||
|
.delta
|
||||||
|
.abs()
|
||||||
|
.cmp(&left.delta.abs())
|
||||||
|
.then_with(|| left_key.cmp(right_key))
|
||||||
|
});
|
||||||
|
let total = causes
|
||||||
|
.iter()
|
||||||
|
.map(|(_, cause)| cause.delta)
|
||||||
|
.sum::<i32>()
|
||||||
|
.clamp(-i32::from(MAX_ATTITUDE), i32::from(MAX_ATTITUDE));
|
||||||
|
Opinion {
|
||||||
|
total,
|
||||||
|
causes: causes.into_iter().map(|(_, cause)| cause).collect(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every subject `holder` has a nonzero opinion of, in subject order. The
|
||||||
|
/// candidates come from the holder's own rows, so the cost follows what the
|
||||||
|
/// holder feels, never the size of the world.
|
||||||
|
pub(crate) fn opinions_held(state: &WorldState, holder: SubjectId) -> BTreeMap<SubjectId, Opinion> {
|
||||||
|
let Some(rows) = state.attitudes.get(&holder) else {
|
||||||
|
return BTreeMap::new();
|
||||||
|
};
|
||||||
|
let mut candidates: BTreeSet<SubjectId> = BTreeSet::new();
|
||||||
|
for key in rows.keys() {
|
||||||
|
match &key.toward {
|
||||||
|
AttitudeToward::Subject(target) => {
|
||||||
|
candidates.insert(*target);
|
||||||
|
}
|
||||||
|
AttitudeToward::Trait(name) => candidates.extend(
|
||||||
|
state
|
||||||
|
.traits
|
||||||
|
.iter()
|
||||||
|
.filter(|(_, carried)| carried.contains_key(name))
|
||||||
|
.map(|(subject, _)| *subject),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
candidates
|
||||||
|
.into_iter()
|
||||||
|
.map(|subject| (subject, opinion(state, holder, subject)))
|
||||||
|
.filter(|(_, held)| !held.causes.is_empty())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The write: add `delta` to the modifier at `key`, saturating at
|
||||||
|
/// `MAX_ATTITUDE`, and restamp it. A modifier summed to zero is removed, so
|
||||||
|
/// absence is the only zero. Saturation at the bound is a legal write that
|
||||||
|
/// renews the term, which is what a grudge piling on a grudge is.
|
||||||
|
pub(crate) fn adjust(
|
||||||
|
state: &mut WorldState,
|
||||||
|
holder: SubjectId,
|
||||||
|
key: AttitudeKey,
|
||||||
|
delta: i16,
|
||||||
|
decay: Option<TickMinutes>,
|
||||||
|
) {
|
||||||
|
let held = state.attitudes.entry(holder).or_default();
|
||||||
|
let current = held.get(&key).map_or(0, |modifier| i32::from(modifier.delta));
|
||||||
|
let next = (current + i32::from(delta))
|
||||||
|
.clamp(-i32::from(MAX_ATTITUDE), i32::from(MAX_ATTITUDE)) as i16;
|
||||||
|
if next == 0 {
|
||||||
|
held.remove(&key);
|
||||||
|
if held.is_empty() {
|
||||||
|
state.attitudes.remove(&holder);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
held.insert(
|
||||||
|
key,
|
||||||
|
AttitudeModifier {
|
||||||
|
delta: next,
|
||||||
|
since: state.now,
|
||||||
|
decay,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The deed's cause: a fall in regard is a grievance and a rise is a favor,
|
||||||
|
/// both named for the command that did it.
|
||||||
|
pub(crate) fn deed_cause(delta: i16, command: CommandId) -> AttitudeCause {
|
||||||
|
if delta < 0 {
|
||||||
|
AttitudeCause::Grievance { command }
|
||||||
|
} else {
|
||||||
|
AttitudeCause::Favor { command }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A delta an author or a world may write: nonzero, within the bound.
|
||||||
|
pub(crate) fn is_valid_delta(delta: i16) -> bool {
|
||||||
|
delta != 0 && delta.unsigned_abs() <= MAX_ATTITUDE.unsigned_abs()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A fade the clock can carry: one minute to a year, the span bound every
|
||||||
|
/// other period in the kernel obeys. `TickMinutes` is transparent in serde, so
|
||||||
|
/// a decoded zero is possible and refused here.
|
||||||
|
pub(crate) fn is_valid_decay(decay: Option<TickMinutes>) -> bool {
|
||||||
|
decay.is_none_or(|span| TickMinutes::new(span.minutes()).is_some())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The one wording of a derived opinion's size, so the Dungeon Master's table,
|
||||||
|
/// a Persona's own view, and the narrator name the same feeling for the same
|
||||||
|
/// number. Reads after "regards them with".
|
||||||
|
pub(crate) fn regard_word(total: i32) -> &'static str {
|
||||||
|
match total {
|
||||||
|
..=-70 => "hatred",
|
||||||
|
-69..=-35 => "hostility",
|
||||||
|
-34..=-10 => "resentment",
|
||||||
|
-9..=9 => "indifference",
|
||||||
|
10..=34 => "liking",
|
||||||
|
35..=69 => "warmth",
|
||||||
|
_ => "devotion",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One cause as a clause a reader can act on. The statement of a rumour is the
|
||||||
|
/// fact the holder believes, resolved by the caller from its own view.
|
||||||
|
pub(crate) fn describe_cause(
|
||||||
|
cause: &OpinionCause,
|
||||||
|
fact_statement: impl Fn(EntityId) -> Option<String>,
|
||||||
|
) -> String {
|
||||||
|
let weight = format!("{:+}", cause.delta);
|
||||||
|
match (&cause.cause, &cause.toward) {
|
||||||
|
(AttitudeCause::Prejudice, AttitudeToward::Trait(name)) => {
|
||||||
|
format!("prejudice toward the {} ({weight})", name.0)
|
||||||
|
}
|
||||||
|
(AttitudeCause::Prejudice, AttitudeToward::Subject(_)) => {
|
||||||
|
format!("a feeling it cannot account for ({weight})")
|
||||||
|
}
|
||||||
|
(AttitudeCause::Grievance { .. }, _) => format!("a grievance ({weight})"),
|
||||||
|
(AttitudeCause::Favor { .. }, _) => format!("a favor owed ({weight})"),
|
||||||
|
(AttitudeCause::Rumour { fact }, _) => match fact_statement(*fact) {
|
||||||
|
Some(statement) => format!("a rumour it believes, \"{statement}\" ({weight})"),
|
||||||
|
None => format!("a rumour it believes ({weight})"),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
670
crates/ghostlight/src/clock_tests/attitude_tests.rs
Normal file
670
crates/ghostlight/src/clock_tests/attitude_tests.rs
Normal file
|
|
@ -0,0 +1,670 @@
|
||||||
|
//! Attitude is kernel state: sourced modifiers, a derived opinion, prejudice
|
||||||
|
//! gated on what the holder knows. Every test here goes through the reducer's
|
||||||
|
//! own doors (a patch or an affordance) and reads the derived opinion back.
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
use crate::attitude::{self, AttitudeCause, AttitudeToward};
|
||||||
|
use crate::attitude::{AttitudeBasisRef, AttitudeTowardRef, TraitName};
|
||||||
|
|
||||||
|
const OUTLANDER: &str = "The farmer came over the pass from the outland.";
|
||||||
|
|
||||||
|
fn play_patch(
|
||||||
|
kernel: &mut WorldKernel,
|
||||||
|
patch: WorldPatch,
|
||||||
|
) -> Result<SubmitReceipt, KernelError> {
|
||||||
|
submit_as(
|
||||||
|
kernel,
|
||||||
|
play_caller(),
|
||||||
|
CommandBody::AdmitPatch {
|
||||||
|
answers: None,
|
||||||
|
patch,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fact_with(kernel: &WorldKernel, statement: &str) -> EntityId {
|
||||||
|
*kernel
|
||||||
|
.state
|
||||||
|
.facts
|
||||||
|
.iter()
|
||||||
|
.find(|(_, record)| record.statement.as_str() == statement)
|
||||||
|
.expect("the declared fact")
|
||||||
|
.0
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ruled_fact(handle: &str, statement: &str) -> Declaration {
|
||||||
|
Declaration::Fact(FactDeclaration {
|
||||||
|
handle: DraftHandle::new(handle),
|
||||||
|
label: "A ruling".into(),
|
||||||
|
statement: Statement::new(statement).unwrap(),
|
||||||
|
standing: FactStandingRef::Ruled,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn learn(
|
||||||
|
kernel: &mut WorldKernel,
|
||||||
|
subject: SubjectId,
|
||||||
|
fact: EntityId,
|
||||||
|
confidence: Confidence,
|
||||||
|
) -> Result<SubmitReceipt, KernelError> {
|
||||||
|
play_patch(
|
||||||
|
kernel,
|
||||||
|
WorldPatch {
|
||||||
|
declarations: Vec::new(),
|
||||||
|
operations: vec![ComponentOp::AcquireKnowledge {
|
||||||
|
subject: Ref::Existing(subject),
|
||||||
|
fact: Ref::Existing(fact),
|
||||||
|
source: AuthoredSource::Witnessed,
|
||||||
|
confidence,
|
||||||
|
}],
|
||||||
|
evidence: Vec::new(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn regard(kernel: &WorldKernel, holder: SubjectId, subject: SubjectId) -> attitude::Opinion {
|
||||||
|
attitude::opinion(&kernel.state, holder, subject)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A reeve who is prejudiced against outlanders, and a farmer who is one.
|
||||||
|
fn outlander_world(path: &Path) -> (WorldKernel, Clockwork, EntityId) {
|
||||||
|
let (mut kernel, clockwork, _) = clock_kernel(path, "Outlanders");
|
||||||
|
play_patch(
|
||||||
|
&mut kernel,
|
||||||
|
WorldPatch {
|
||||||
|
declarations: vec![ruled_fact("outland", OUTLANDER)],
|
||||||
|
operations: vec![
|
||||||
|
ComponentOp::DeclareTrait {
|
||||||
|
subject: Ref::Existing(clockwork.farmer),
|
||||||
|
name: TraitName("outlander".into()),
|
||||||
|
fact: Ref::Draft(DraftHandle::new("outland")),
|
||||||
|
},
|
||||||
|
ComponentOp::DeclareAttitude {
|
||||||
|
holder: Ref::Existing(clockwork.reeve),
|
||||||
|
toward: AttitudeTowardRef::Trait(TraitName("outlander".into())),
|
||||||
|
delta: -40,
|
||||||
|
basis: AttitudeBasisRef::Prejudice,
|
||||||
|
decay: None,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
evidence: Vec::new(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.expect("the play authority declares the trait and the prejudice");
|
||||||
|
let fact = fact_with(&kernel, OUTLANDER);
|
||||||
|
(kernel, clockwork, fact)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A world-authored `insult`: the target comes to regard the actor 30 lower.
|
||||||
|
fn grant_insult(kernel: &mut WorldKernel, to: SubjectId, delta: i16, decay: Option<TickMinutes>) {
|
||||||
|
play_patch(
|
||||||
|
kernel,
|
||||||
|
WorldPatch {
|
||||||
|
declarations: vec![Declaration::Affordance(AffordanceDeclaration {
|
||||||
|
handle: DraftHandle::new("insult"),
|
||||||
|
kind: AffordanceKindName("insult".into()),
|
||||||
|
roles: vec![RoleSpec {
|
||||||
|
role: Role("target".into()),
|
||||||
|
kind: RefKind::Subject(None),
|
||||||
|
}],
|
||||||
|
preconditions: Vec::new(),
|
||||||
|
effect_slots: vec![EffectSlot {
|
||||||
|
op_kind: ComponentOpKind::AdjustAttitude { delta, decay },
|
||||||
|
roles: vec![Role("target".into())],
|
||||||
|
bounds: Bounds::None,
|
||||||
|
}],
|
||||||
|
outcome_bands: vec![OutcomeBand {
|
||||||
|
weight: 1,
|
||||||
|
effects: vec![0],
|
||||||
|
}],
|
||||||
|
carries_speech: false,
|
||||||
|
})],
|
||||||
|
operations: vec![ComponentOp::GrantAffordance {
|
||||||
|
subject: Ref::Existing(to),
|
||||||
|
affordance: Ref::Draft(DraftHandle::new("insult")),
|
||||||
|
}],
|
||||||
|
evidence: Vec::new(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.expect("the world authors and grants the verb");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn insult_id(kernel: &WorldKernel) -> AffordanceId {
|
||||||
|
*kernel
|
||||||
|
.state
|
||||||
|
.affordance_catalog
|
||||||
|
.iter()
|
||||||
|
.find(|(_, entry)| entry.kind.0 == "insult")
|
||||||
|
.expect("the insult entry")
|
||||||
|
.0
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn prejudice_needs_belief() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let (mut kernel, clockwork, fact) = outlander_world(directory.path());
|
||||||
|
|
||||||
|
// The holder has not heard the farmer is an outlander: no opinion at all.
|
||||||
|
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.farmer).total, 0);
|
||||||
|
assert!(kernel.snapshot().unwrap().subjects.iter().all(|s| s.opinions.is_empty()));
|
||||||
|
|
||||||
|
// Somebody else knowing it does not move the reeve.
|
||||||
|
learn(&mut kernel, clockwork.treasury, fact, Confidence::Certain).unwrap();
|
||||||
|
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.farmer).total, 0);
|
||||||
|
|
||||||
|
// A doubted telling does not either.
|
||||||
|
learn(&mut kernel, clockwork.reeve, fact, Confidence::Doubted).unwrap();
|
||||||
|
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.farmer).total, 0);
|
||||||
|
|
||||||
|
// Believed, it does, for the farmer and for nobody who is not one.
|
||||||
|
learn(&mut kernel, clockwork.reeve, fact, Confidence::Believed).unwrap();
|
||||||
|
let held = regard(&kernel, clockwork.reeve, clockwork.farmer);
|
||||||
|
assert_eq!(held.total, -40);
|
||||||
|
assert_eq!(held.causes[0].cause, AttitudeCause::Prejudice);
|
||||||
|
assert_eq!(
|
||||||
|
held.causes[0].toward,
|
||||||
|
AttitudeToward::Trait(TraitName("outlander".into()))
|
||||||
|
);
|
||||||
|
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.treasury).total, 0);
|
||||||
|
assert_eq!(
|
||||||
|
regard(&kernel, clockwork.farmer, clockwork.reeve).total,
|
||||||
|
0,
|
||||||
|
"regard does not run backward"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Forgetting it lifts the prejudice: the opinion is derived, not stored.
|
||||||
|
play_patch(
|
||||||
|
&mut kernel,
|
||||||
|
WorldPatch {
|
||||||
|
declarations: Vec::new(),
|
||||||
|
operations: vec![ComponentOp::Forget {
|
||||||
|
subject: Ref::Existing(clockwork.reeve),
|
||||||
|
fact: Ref::Existing(fact),
|
||||||
|
}],
|
||||||
|
evidence: Vec::new(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.farmer).total, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn grievance_from_an_act() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Grievance");
|
||||||
|
grant_insult(&mut kernel, clockwork.farmer, -30, None);
|
||||||
|
let insult = insult_id(&kernel);
|
||||||
|
|
||||||
|
exercise(
|
||||||
|
&mut kernel,
|
||||||
|
clockwork.farmer,
|
||||||
|
insult,
|
||||||
|
vec![binding("target", Target::Subject(clockwork.reeve))],
|
||||||
|
)
|
||||||
|
.expect("the insult commits");
|
||||||
|
let held = regard(&kernel, clockwork.reeve, clockwork.farmer);
|
||||||
|
assert_eq!(held.total, -30);
|
||||||
|
assert!(matches!(
|
||||||
|
held.causes[0].cause,
|
||||||
|
AttitudeCause::Grievance { .. }
|
||||||
|
));
|
||||||
|
assert_eq!(
|
||||||
|
regard(&kernel, clockwork.farmer, clockwork.reeve).total,
|
||||||
|
0,
|
||||||
|
"the insulter does not come to resent the insulted"
|
||||||
|
);
|
||||||
|
|
||||||
|
// A second insult is a second act with its own cause; they add.
|
||||||
|
exercise(
|
||||||
|
&mut kernel,
|
||||||
|
clockwork.farmer,
|
||||||
|
insult,
|
||||||
|
vec![binding("target", Target::Subject(clockwork.reeve))],
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let held = regard(&kernel, clockwork.reeve, clockwork.farmer);
|
||||||
|
assert_eq!(held.total, -60);
|
||||||
|
assert_eq!(held.causes.len(), 2);
|
||||||
|
assert_ne!(held.causes[0].cause, held.causes[1].cause);
|
||||||
|
|
||||||
|
// A favor is the same write with the other sign.
|
||||||
|
play_patch(
|
||||||
|
&mut kernel,
|
||||||
|
WorldPatch {
|
||||||
|
declarations: Vec::new(),
|
||||||
|
operations: vec![ComponentOp::AdjustAttitude {
|
||||||
|
holder: Ref::Existing(clockwork.reeve),
|
||||||
|
toward: Ref::Existing(clockwork.farmer),
|
||||||
|
delta: 20,
|
||||||
|
decay: None,
|
||||||
|
}],
|
||||||
|
evidence: Vec::new(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let held = regard(&kernel, clockwork.reeve, clockwork.farmer);
|
||||||
|
assert_eq!(held.total, -40);
|
||||||
|
assert!(
|
||||||
|
held.causes
|
||||||
|
.iter()
|
||||||
|
.any(|cause| matches!(cause.cause, AttitudeCause::Favor { .. }) && cause.delta == 20)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn regard_saturates_at_the_bound_and_a_clamped_write_is_not_an_error() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Saturation");
|
||||||
|
let wrong = |delta| ComponentOp::AdjustAttitude {
|
||||||
|
holder: Ref::Existing(clockwork.reeve),
|
||||||
|
toward: Ref::Existing(clockwork.farmer),
|
||||||
|
delta,
|
||||||
|
decay: None,
|
||||||
|
};
|
||||||
|
// Three deeds in one command are one row of the same cause, clamped.
|
||||||
|
play_patch(
|
||||||
|
&mut kernel,
|
||||||
|
WorldPatch {
|
||||||
|
declarations: Vec::new(),
|
||||||
|
operations: vec![wrong(-60), wrong(-60), wrong(-60)],
|
||||||
|
evidence: Vec::new(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.expect("a saturated write still commits");
|
||||||
|
let held = regard(&kernel, clockwork.reeve, clockwork.farmer);
|
||||||
|
assert_eq!(held.total, -100);
|
||||||
|
assert_eq!(held.causes.len(), 1);
|
||||||
|
|
||||||
|
// Separate commands pile past one row, and the opinion still clamps.
|
||||||
|
play_patch(
|
||||||
|
&mut kernel,
|
||||||
|
WorldPatch {
|
||||||
|
declarations: Vec::new(),
|
||||||
|
operations: vec![wrong(-60)],
|
||||||
|
evidence: Vec::new(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.farmer).total, -100);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_decaying_term_fades_and_a_grudge_does_not() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Decay");
|
||||||
|
let write = |delta, decay| ComponentOp::AdjustAttitude {
|
||||||
|
holder: Ref::Existing(clockwork.reeve),
|
||||||
|
toward: Ref::Existing(clockwork.farmer),
|
||||||
|
delta,
|
||||||
|
decay,
|
||||||
|
};
|
||||||
|
play_patch(
|
||||||
|
&mut kernel,
|
||||||
|
WorldPatch {
|
||||||
|
declarations: Vec::new(),
|
||||||
|
operations: vec![write(-40, Some(minutes(100)))],
|
||||||
|
evidence: Vec::new(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
play_patch(
|
||||||
|
&mut kernel,
|
||||||
|
WorldPatch {
|
||||||
|
declarations: Vec::new(),
|
||||||
|
operations: vec![write(20, None)],
|
||||||
|
evidence: Vec::new(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.farmer).total, -20);
|
||||||
|
tick(&mut kernel, 50).unwrap();
|
||||||
|
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.farmer).total, 0);
|
||||||
|
tick(&mut kernel, 50).unwrap();
|
||||||
|
let held = regard(&kernel, clockwork.reeve, clockwork.farmer);
|
||||||
|
assert_eq!(held.total, 20, "the faded grievance is gone, the favor stays");
|
||||||
|
assert_eq!(held.causes.len(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_rumour_moves_only_a_holder_who_believes_it() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Rumour");
|
||||||
|
play_patch(
|
||||||
|
&mut kernel,
|
||||||
|
WorldPatch {
|
||||||
|
declarations: vec![ruled_fact("tale", "They say the farmer poisoned a well.")],
|
||||||
|
operations: vec![ComponentOp::DeclareAttitude {
|
||||||
|
holder: Ref::Existing(clockwork.reeve),
|
||||||
|
toward: AttitudeTowardRef::Subject(Ref::Existing(clockwork.farmer)),
|
||||||
|
delta: -25,
|
||||||
|
basis: AttitudeBasisRef::Rumour {
|
||||||
|
fact: Ref::Draft(DraftHandle::new("tale")),
|
||||||
|
},
|
||||||
|
decay: None,
|
||||||
|
}],
|
||||||
|
evidence: Vec::new(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let tale = fact_with(&kernel, "They say the farmer poisoned a well.");
|
||||||
|
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.farmer).total, 0);
|
||||||
|
learn(&mut kernel, clockwork.reeve, tale, Confidence::Believed).unwrap();
|
||||||
|
let held = regard(&kernel, clockwork.reeve, clockwork.farmer);
|
||||||
|
assert_eq!(held.total, -25);
|
||||||
|
assert_eq!(held.causes[0].cause, AttitudeCause::Rumour { fact: tale });
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn attitude_writes_with_no_meaning_are_refused_whole() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let (mut kernel, clockwork, fact) = outlander_world(directory.path());
|
||||||
|
let before = kernel.state.clone();
|
||||||
|
let adjust = |delta, holder, toward| ComponentOp::AdjustAttitude {
|
||||||
|
holder: Ref::Existing(holder),
|
||||||
|
toward: Ref::Existing(toward),
|
||||||
|
delta,
|
||||||
|
decay: None,
|
||||||
|
};
|
||||||
|
let refused: Vec<(&str, ComponentOp)> = vec![
|
||||||
|
("zero delta", adjust(0, clockwork.reeve, clockwork.farmer)),
|
||||||
|
("past the bound", adjust(101, clockwork.reeve, clockwork.farmer)),
|
||||||
|
("regarding oneself", adjust(-5, clockwork.reeve, clockwork.reeve)),
|
||||||
|
(
|
||||||
|
"a zero decay",
|
||||||
|
ComponentOp::AdjustAttitude {
|
||||||
|
holder: Ref::Existing(clockwork.reeve),
|
||||||
|
toward: Ref::Existing(clockwork.farmer),
|
||||||
|
delta: -5,
|
||||||
|
decay: serde_json::from_value(serde_json::json!(0)).unwrap(),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"a rumour of a trait",
|
||||||
|
ComponentOp::DeclareAttitude {
|
||||||
|
holder: Ref::Existing(clockwork.reeve),
|
||||||
|
toward: AttitudeTowardRef::Trait(TraitName("outlander".into())),
|
||||||
|
delta: -5,
|
||||||
|
basis: AttitudeBasisRef::Rumour {
|
||||||
|
fact: Ref::Existing(fact),
|
||||||
|
},
|
||||||
|
decay: None,
|
||||||
|
},
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"a trait that is not a name",
|
||||||
|
ComponentOp::DeclareAttitude {
|
||||||
|
holder: Ref::Existing(clockwork.reeve),
|
||||||
|
toward: AttitudeTowardRef::Trait(TraitName("Not A Name".into())),
|
||||||
|
delta: -5,
|
||||||
|
basis: AttitudeBasisRef::Prejudice,
|
||||||
|
decay: None,
|
||||||
|
},
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"a trait declared with a bad name",
|
||||||
|
ComponentOp::DeclareTrait {
|
||||||
|
subject: Ref::Existing(clockwork.farmer),
|
||||||
|
name: TraitName("".into()),
|
||||||
|
fact: Ref::Existing(fact),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
];
|
||||||
|
for (name, operation) in refused {
|
||||||
|
let error = play_patch(
|
||||||
|
&mut kernel,
|
||||||
|
WorldPatch {
|
||||||
|
declarations: Vec::new(),
|
||||||
|
operations: vec![operation],
|
||||||
|
evidence: Vec::new(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.expect_err(name);
|
||||||
|
assert!(
|
||||||
|
format!("{error:?}").contains("InvalidAttitude"),
|
||||||
|
"{name}: {error:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// An affordance whose delta is nothing is refused at declaration.
|
||||||
|
let error = play_patch(
|
||||||
|
&mut kernel,
|
||||||
|
WorldPatch {
|
||||||
|
declarations: vec![Declaration::Affordance(AffordanceDeclaration {
|
||||||
|
handle: DraftHandle::new("nothing"),
|
||||||
|
kind: AffordanceKindName("nothing".into()),
|
||||||
|
roles: vec![RoleSpec {
|
||||||
|
role: Role("target".into()),
|
||||||
|
kind: RefKind::Subject(None),
|
||||||
|
}],
|
||||||
|
preconditions: Vec::new(),
|
||||||
|
effect_slots: vec![EffectSlot {
|
||||||
|
op_kind: ComponentOpKind::AdjustAttitude {
|
||||||
|
delta: 0,
|
||||||
|
decay: None,
|
||||||
|
},
|
||||||
|
roles: vec![Role("target".into())],
|
||||||
|
bounds: Bounds::None,
|
||||||
|
}],
|
||||||
|
outcome_bands: vec![OutcomeBand {
|
||||||
|
weight: 1,
|
||||||
|
effects: vec![0],
|
||||||
|
}],
|
||||||
|
carries_speech: false,
|
||||||
|
})],
|
||||||
|
operations: Vec::new(),
|
||||||
|
evidence: Vec::new(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.expect_err("an entry that changes no regard");
|
||||||
|
assert!(format!("{error:?}").contains("InvalidAttitude"), "{error:?}");
|
||||||
|
assert_eq!(kernel.state, before, "a refused write leaves no trace");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_derived_opinion_and_its_causes_reach_the_tables_view() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let (mut kernel, clockwork, fact) = outlander_world(directory.path());
|
||||||
|
grant_insult(&mut kernel, clockwork.farmer, -30, None);
|
||||||
|
let insult = insult_id(&kernel);
|
||||||
|
learn(&mut kernel, clockwork.reeve, fact, Confidence::Believed).unwrap();
|
||||||
|
exercise(
|
||||||
|
&mut kernel,
|
||||||
|
clockwork.farmer,
|
||||||
|
insult,
|
||||||
|
vec![binding("target", Target::Subject(clockwork.reeve))],
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let snapshot = kernel.snapshot().unwrap();
|
||||||
|
let reeve = snapshot
|
||||||
|
.subjects
|
||||||
|
.iter()
|
||||||
|
.find(|subject| subject.id == clockwork.reeve)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(reeve.opinions.len(), 1);
|
||||||
|
assert_eq!(reeve.opinions[0].toward, clockwork.farmer);
|
||||||
|
assert_eq!(reeve.opinions[0].total, -70);
|
||||||
|
assert_eq!(reeve.opinions[0].causes.len(), 2);
|
||||||
|
|
||||||
|
let view = crate::table_view(&snapshot);
|
||||||
|
let line = view
|
||||||
|
.split("Regard")
|
||||||
|
.nth(1)
|
||||||
|
.and_then(|rest| rest.split("Persona material").next())
|
||||||
|
.expect("the table has a regard section");
|
||||||
|
assert!(line.contains("The Yard Reeve"), "{line}");
|
||||||
|
assert!(line.contains("regards The Yard Farmer"), "{line}");
|
||||||
|
assert!(line.contains("with hatred (-70)"), "{line}");
|
||||||
|
assert!(line.contains("(-70)"), "{line}");
|
||||||
|
assert!(line.contains("a grievance (-30)"), "{line}");
|
||||||
|
assert!(line.contains("prejudice toward the outlander (-40)"), "{line}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An act the room saw: the same invocation as `exercise`, with the actor's own
|
||||||
|
/// words for what everyone present watched.
|
||||||
|
fn exercise_displaying(
|
||||||
|
kernel: &mut WorldKernel,
|
||||||
|
actor: SubjectId,
|
||||||
|
affordance: AffordanceId,
|
||||||
|
bindings: Vec<RoleBinding>,
|
||||||
|
display: &str,
|
||||||
|
) -> Result<SubmitReceipt, KernelError> {
|
||||||
|
let snapshot = kernel.snapshot().unwrap();
|
||||||
|
let opportunity = opportunity_for(&snapshot, actor);
|
||||||
|
let caller = CallerId::Controller(opportunity.controller_id);
|
||||||
|
kernel.submit(
|
||||||
|
command(
|
||||||
|
&snapshot,
|
||||||
|
CommandId::new(),
|
||||||
|
caller.clone(),
|
||||||
|
CommandBody::ExerciseDecision {
|
||||||
|
opportunity,
|
||||||
|
invocation: DecisionInvocation {
|
||||||
|
affordance,
|
||||||
|
bindings,
|
||||||
|
proposed: vec![ProposedEffect {
|
||||||
|
slot: 0,
|
||||||
|
magnitude: Magnitude::None,
|
||||||
|
}],
|
||||||
|
speech: None,
|
||||||
|
display: Some(Statement::new(display).unwrap()),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
),
|
||||||
|
&AuthenticatedCaller::fixture(caller),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
use crate::clock::FictionalMinutes;
|
||||||
|
use crate::patch::{CommitmentKind, PressureMagnitude};
|
||||||
|
|
||||||
|
const BLOW: &str = "The farmer strikes the reeve.";
|
||||||
|
|
||||||
|
/// The view's Open grievances block, alone.
|
||||||
|
fn open_grievances(kernel: &WorldKernel) -> String {
|
||||||
|
let view = crate::table_view(&kernel.snapshot().unwrap());
|
||||||
|
view.split("Open grievances")
|
||||||
|
.nth(1)
|
||||||
|
.expect("the view always carries the block")
|
||||||
|
.split("\n Persona material")
|
||||||
|
.next()
|
||||||
|
.unwrap()
|
||||||
|
.to_owned()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn segment<'a>(text: &'a str, from: &str, to: &str) -> &'a str {
|
||||||
|
let start = text.find(from).unwrap_or_else(|| panic!("`{from}` missing in {text}")) + from.len();
|
||||||
|
let end = start + text[start..].find(to).unwrap_or(text.len() - start);
|
||||||
|
&text[start..end]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn strike(kernel: &mut WorldKernel, clockwork: &Clockwork, delta: i16) {
|
||||||
|
grant_insult(kernel, clockwork.farmer, delta, None);
|
||||||
|
let insult = insult_id(kernel);
|
||||||
|
exercise_displaying(
|
||||||
|
kernel,
|
||||||
|
clockwork.farmer,
|
||||||
|
insult,
|
||||||
|
vec![binding("target", Target::Subject(clockwork.reeve))],
|
||||||
|
BLOW,
|
||||||
|
)
|
||||||
|
.expect("the blow commits");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_deed_the_room_saw_is_an_open_grievance_until_something_answers_it() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Open grievances");
|
||||||
|
assert!(open_grievances(&kernel).trim().ends_with("none"));
|
||||||
|
|
||||||
|
strike(&mut kernel, &clockwork, -30);
|
||||||
|
let block = open_grievances(&kernel);
|
||||||
|
assert_eq!(block.matches("; acts seen by:").count(), 1, "one doer, no other: {block}");
|
||||||
|
assert!(block.contains("The Yard Farmer"), "{block}");
|
||||||
|
assert!(segment(&block, "wronged", ";").contains("The Yard Reeve"), "{block}");
|
||||||
|
let seen = segment(&block, "acts seen by:", "forums covering");
|
||||||
|
assert!(seen.contains("The Yard Reeve") && seen.contains(BLOW), "{seen}");
|
||||||
|
assert!(!seen.contains("The Yard Farmer"), "the doer is not their own witness: {seen}");
|
||||||
|
assert!(segment(&block, "forums covering them:", ";").contains("none"), "{block}");
|
||||||
|
assert!(segment(&block, "pressed by:", ";").contains("no one"), "{block}");
|
||||||
|
assert!(segment(&block, "reckonings sworn against them:", ";").contains("none"), "{block}");
|
||||||
|
assert!(block.contains("nothing has answered it yet"), "{block}");
|
||||||
|
|
||||||
|
// Someone leans on the doer: answered, and the pressure is named with its weight.
|
||||||
|
play_patch(
|
||||||
|
&mut kernel,
|
||||||
|
WorldPatch {
|
||||||
|
declarations: Vec::new(),
|
||||||
|
operations: vec![ComponentOp::AdvancePressure {
|
||||||
|
source: PressureSourceRef::Subject(Ref::Existing(clockwork.reeve)),
|
||||||
|
target: Ref::Existing(clockwork.farmer),
|
||||||
|
by: PressureMagnitude(30),
|
||||||
|
}],
|
||||||
|
evidence: Vec::new(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let block = open_grievances(&kernel);
|
||||||
|
let pressed = segment(&block, "pressed by:", ";");
|
||||||
|
assert!(pressed.contains("The Yard Reeve") && pressed.contains("(30)"), "{pressed}");
|
||||||
|
assert!(block.contains("answered so far") && !block.contains("nothing has answered"), "{block}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_sworn_reckoning_answers_a_grievance_and_a_favour_opens_none() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Reckoning");
|
||||||
|
strike(&mut kernel, &clockwork, -30);
|
||||||
|
play_patch(
|
||||||
|
&mut kernel,
|
||||||
|
WorldPatch {
|
||||||
|
declarations: Vec::new(),
|
||||||
|
operations: vec![ComponentOp::CreateCommitment {
|
||||||
|
subject: Ref::Existing(clockwork.reeve),
|
||||||
|
counterparty: Some(Ref::Existing(clockwork.farmer)),
|
||||||
|
kind: CommitmentKind::Obligation,
|
||||||
|
due: FictionalMinutes(600),
|
||||||
|
period: None,
|
||||||
|
checks: Vec::new(),
|
||||||
|
statement: Statement::new("Make the farmer answer for the blow.").unwrap(),
|
||||||
|
}],
|
||||||
|
evidence: Vec::new(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let block = open_grievances(&kernel);
|
||||||
|
let sworn = segment(&block, "reckonings sworn against them:", "answered");
|
||||||
|
assert!(sworn.contains("The Yard Reeve") && sworn.contains("Make the farmer answer"), "{sworn}");
|
||||||
|
assert!(segment(&block, "pressed by:", ";").contains("no one"), "{block}");
|
||||||
|
assert!(block.contains("answered so far"), "{block}");
|
||||||
|
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let (mut kindly, clockwork, _) = clock_kernel(directory.path(), "Favour");
|
||||||
|
strike(&mut kindly, &clockwork, 20);
|
||||||
|
assert!(open_grievances(&kindly).trim().ends_with("none"), "a favour is no grievance");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_dislike_nobody_earned_is_no_open_grievance() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Prejudice");
|
||||||
|
play_patch(
|
||||||
|
&mut kernel,
|
||||||
|
WorldPatch {
|
||||||
|
declarations: Vec::new(),
|
||||||
|
operations: vec![ComponentOp::DeclareAttitude {
|
||||||
|
holder: Ref::Existing(clockwork.reeve),
|
||||||
|
toward: AttitudeTowardRef::Subject(Ref::Existing(clockwork.farmer)),
|
||||||
|
delta: -40,
|
||||||
|
basis: AttitudeBasisRef::Prejudice,
|
||||||
|
decay: None,
|
||||||
|
}],
|
||||||
|
evidence: Vec::new(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(regard(&kernel, clockwork.reeve, clockwork.farmer).total, -40);
|
||||||
|
assert!(
|
||||||
|
open_grievances(&kernel).trim().ends_with("none"),
|
||||||
|
"a feeling no deed explains wrongs no one"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -469,7 +469,7 @@ mod tests {
|
||||||
AuthorityTargetRef, CallerId, CausalBoundary, CommandBody, CommandEnvelope, CommitmentKind,
|
AuthorityTargetRef, CallerId, CausalBoundary, CommandBody, CommandEnvelope, CommitmentKind,
|
||||||
ComponentOp, CoverBudget, DecisionOpportunity, DecisionScope, Declaration, DraftHandle,
|
ComponentOp, CoverBudget, DecisionOpportunity, DecisionScope, Declaration, DraftHandle,
|
||||||
EntityDeclaration, EntityId, EntityKind, EvidenceRef, FactDeclaration, FactStandingRef,
|
EntityDeclaration, EntityId, EntityKind, EvidenceRef, FactDeclaration, FactStandingRef,
|
||||||
FictionalMinutes, JurisdictionKey, NewController, PatchGround, Quantity, Ref,
|
FictionalMinutes, JurisdictionKey, NewController, PatchGround, Quantity, Ref, TickIndex,
|
||||||
RouteDeclaration, Statement, SubjectDeclaration, SubjectId, SubjectKind, SystemCapability,
|
RouteDeclaration, Statement, SubjectDeclaration, SubjectId, SubjectKind, SystemCapability,
|
||||||
WorldEffect, WorldId, WorldKernel, WorldMailbox, WorldScaleIntentRef, agency_graph,
|
WorldEffect, WorldId, WorldKernel, WorldMailbox, WorldScaleIntentRef, agency_graph,
|
||||||
commit_digest, derive_boundaries, derive_cover, derive_opportunities,
|
commit_digest, derive_boundaries, derive_cover, derive_opportunities,
|
||||||
|
|
@ -518,6 +518,7 @@ mod tests {
|
||||||
},
|
},
|
||||||
controller,
|
controller,
|
||||||
position: Some(Ref::Existing(commons)),
|
position: Some(Ref::Existing(commons)),
|
||||||
|
import_key: None,
|
||||||
})
|
})
|
||||||
};
|
};
|
||||||
WorldPatch {
|
WorldPatch {
|
||||||
|
|
@ -735,8 +736,7 @@ mod tests {
|
||||||
assert!(!graph.subjects.contains(&mirror.first));
|
assert!(!graph.subjects.contains(&mirror.first));
|
||||||
let cover = derive_cover(
|
let cover = derive_cover(
|
||||||
snapshot.world_id,
|
snapshot.world_id,
|
||||||
snapshot.now,
|
TickIndex(0),
|
||||||
30,
|
|
||||||
&opportunities,
|
&opportunities,
|
||||||
&graph,
|
&graph,
|
||||||
CoverBudget {
|
CoverBudget {
|
||||||
|
|
@ -1195,6 +1195,7 @@ mod tests {
|
||||||
controller: NewController::External { consumer },
|
controller: NewController::External { consumer },
|
||||||
affordances: BTreeSet::new(),
|
affordances: BTreeSet::new(),
|
||||||
position: Some(Ref::Existing(commons)),
|
position: Some(Ref::Existing(commons)),
|
||||||
|
import_key: None,
|
||||||
})])
|
})])
|
||||||
};
|
};
|
||||||
// A binding to another consumer is outside its ground.
|
// A binding to another consumer is outside its ground.
|
||||||
|
|
@ -1573,6 +1574,7 @@ mod tests {
|
||||||
controller,
|
controller,
|
||||||
affordances,
|
affordances,
|
||||||
position: Some(Ref::Existing(mirror.commons)),
|
position: Some(Ref::Existing(mirror.commons)),
|
||||||
|
import_key: None,
|
||||||
})])
|
})])
|
||||||
};
|
};
|
||||||
let pairing = |result: Result<SubmitReceipt, KernelError>| {
|
let pairing = |result: Result<SubmitReceipt, KernelError>| {
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -11,7 +11,6 @@
|
||||||
//! The cover is a partition, never a filter: every active subject is in exactly
|
//! The cover is a partition, never a filter: every active subject is in exactly
|
||||||
//! one cell every tick. The budget decides at what resolution, not whether.
|
//! one cell every tick. The budget decides at what resolution, not whether.
|
||||||
|
|
||||||
use super::clock::FictionalMinutes;
|
|
||||||
use super::{ControllerMode, DecisionOpportunity, SubjectId, WorldId};
|
use super::{ControllerMode, DecisionOpportunity, SubjectId, WorldId};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use sha2::{Digest, Sha256};
|
use sha2::{Digest, Sha256};
|
||||||
|
|
@ -29,25 +28,18 @@ pub(crate) const AGENCY_STAR_THRESHOLD: usize = 16;
|
||||||
/// the name, not by a second namespace.
|
/// the name, not by a second namespace.
|
||||||
const COVER_NAMESPACE: &str = "ghostlight.cover.v1";
|
const COVER_NAMESPACE: &str = "ghostlight.cover.v1";
|
||||||
|
|
||||||
/// Monotone tick index. Derived from the world clock, never stored. It is
|
/// A tick's ordinal: the number of clock advances the world had committed when
|
||||||
/// threaded into every derived command id, so a resumed tick over the same
|
/// the tick opened. The driver reads it from the world and freezes it in the
|
||||||
/// snapshot re-derives the same ids and the kernel's idempotency ledger answers
|
/// tick document; it is never derived from `now`, so it does not depend on the
|
||||||
/// with the original receipts instead of double-committing.
|
/// span. It is threaded into every derived command id, so a resumed tick
|
||||||
|
/// re-submits the same ids and the kernel's idempotency ledger answers with the
|
||||||
|
/// original receipts instead of double-committing.
|
||||||
#[derive(
|
#[derive(
|
||||||
Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Default,
|
Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Default,
|
||||||
)]
|
)]
|
||||||
#[serde(transparent)]
|
#[serde(transparent)]
|
||||||
pub struct TickIndex(pub u64);
|
pub struct TickIndex(pub u64);
|
||||||
|
|
||||||
impl TickIndex {
|
|
||||||
/// Floor division by the span one `AdvanceTime` carries. The driver submits
|
|
||||||
/// the clock *after* the cells run, so every cell in one tick sees the same
|
|
||||||
/// `now` and therefore the same index.
|
|
||||||
pub(crate) fn of(now: FictionalMinutes, tick_minutes: u32) -> Self {
|
|
||||||
Self(now.0 / u64::from(tick_minutes.max(1)))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// How a subject was represented this tick. Derived from the cell, carried
|
/// How a subject was represented this tick. Derived from the cell, carried
|
||||||
/// nowhere in world state: representation is a compute budget, not world truth.
|
/// nowhere in world state: representation is a compute budget, not world truth.
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
|
@ -70,9 +62,12 @@ impl std::fmt::Display for CellId {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn derive_uuid(name: &str) -> Uuid {
|
/// sha256 over a fixed namespace and a name, first sixteen bytes: the one id
|
||||||
|
/// recipe the scheduler's derived ids share (cells here, hierarchy nodes in
|
||||||
|
/// `hierarchy.rs`), so the two cannot drift apart.
|
||||||
|
pub(crate) fn derive_uuid(namespace: &str, name: &str) -> Uuid {
|
||||||
let mut hasher = Sha256::new();
|
let mut hasher = Sha256::new();
|
||||||
hasher.update(COVER_NAMESPACE.as_bytes());
|
hasher.update(namespace.as_bytes());
|
||||||
hasher.update([0u8]);
|
hasher.update([0u8]);
|
||||||
hasher.update(name.as_bytes());
|
hasher.update(name.as_bytes());
|
||||||
let bytes: [u8; 16] = hasher.finalize()[..16]
|
let bytes: [u8; 16] = hasher.finalize()[..16]
|
||||||
|
|
@ -89,7 +84,7 @@ fn cell_id(world: WorldId, tick: TickIndex, members: &[SubjectId]) -> CellId {
|
||||||
.first()
|
.first()
|
||||||
.copied()
|
.copied()
|
||||||
.expect("a cell always has at least one member");
|
.expect("a cell always has at least one member");
|
||||||
CellId(derive_uuid(&format!(
|
CellId(derive_uuid(COVER_NAMESPACE, &format!(
|
||||||
"cell|{world:?}|{}|{}|{lowest:?}",
|
"cell|{world:?}|{}|{}|{lowest:?}",
|
||||||
tick.0,
|
tick.0,
|
||||||
members.len()
|
members.len()
|
||||||
|
|
@ -98,7 +93,7 @@ fn cell_id(world: WorldId, tick: TickIndex, members: &[SubjectId]) -> CellId {
|
||||||
|
|
||||||
/// The stable, derived identity a cell's controller-work row is keyed by.
|
/// The stable, derived identity a cell's controller-work row is keyed by.
|
||||||
pub(crate) fn cell_work_uuid(world: WorldId, cell: CellId, tick: TickIndex) -> Uuid {
|
pub(crate) fn cell_work_uuid(world: WorldId, cell: CellId, tick: TickIndex) -> Uuid {
|
||||||
derive_uuid(&format!("cell-work|{world:?}|{cell}|{}", tick.0))
|
derive_uuid(COVER_NAMESPACE, &format!("cell-work|{world:?}|{cell}|{}", tick.0))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One constituent's submission id. Deterministic, so a resumed cell re-submits
|
/// One constituent's submission id. Deterministic, so a resumed cell re-submits
|
||||||
|
|
@ -109,7 +104,7 @@ pub(crate) fn cell_constituent_uuid(
|
||||||
subject: SubjectId,
|
subject: SubjectId,
|
||||||
tick: TickIndex,
|
tick: TickIndex,
|
||||||
) -> Uuid {
|
) -> Uuid {
|
||||||
derive_uuid(&format!("cell-act|{world:?}|{cell}|{subject:?}|{}", tick.0))
|
derive_uuid(COVER_NAMESPACE, &format!("cell-act|{world:?}|{cell}|{subject:?}|{}", tick.0))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
|
@ -241,6 +236,27 @@ impl AgencyGraph {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The adjacency among `members` alone: one node's voices partition over
|
||||||
|
/// the edges that run between them. A star's centre outside `members`
|
||||||
|
/// leaves its rays unlinked, which is honest: they were adjacent through
|
||||||
|
/// somebody who is not at this table.
|
||||||
|
pub(crate) fn restricted(&self, members: &BTreeSet<SubjectId>) -> Self {
|
||||||
|
Self {
|
||||||
|
subjects: self
|
||||||
|
.subjects
|
||||||
|
.iter()
|
||||||
|
.copied()
|
||||||
|
.filter(|subject| members.contains(subject))
|
||||||
|
.collect(),
|
||||||
|
edges: self
|
||||||
|
.edges
|
||||||
|
.iter()
|
||||||
|
.copied()
|
||||||
|
.filter(|(one, other)| members.contains(one) && members.contains(other))
|
||||||
|
.collect(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) fn link(&mut self, one: SubjectId, other: SubjectId) {
|
pub(crate) fn link(&mut self, one: SubjectId, other: SubjectId) {
|
||||||
if one == other {
|
if one == other {
|
||||||
return;
|
return;
|
||||||
|
|
@ -254,7 +270,7 @@ impl AgencyGraph {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The partition. Pure over `(world, now, opportunities, graph, budget)`.
|
/// The partition. Pure over `(world, tick, opportunities, graph, budget)`.
|
||||||
///
|
///
|
||||||
/// `opportunities` arrives in the kernel's one attention order (pressure, then
|
/// `opportunities` arrives in the kernel's one attention order (pressure, then
|
||||||
/// attention debt, then id) and is never re-sorted and never filtered here: a
|
/// attention debt, then id) and is never re-sorted and never filtered here: a
|
||||||
|
|
@ -262,13 +278,11 @@ impl AgencyGraph {
|
||||||
/// is a fact about cognition rather than a scheduling preference.
|
/// is a fact about cognition rather than a scheduling preference.
|
||||||
pub fn derive_cover(
|
pub fn derive_cover(
|
||||||
world: WorldId,
|
world: WorldId,
|
||||||
now: FictionalMinutes,
|
tick: TickIndex,
|
||||||
tick_minutes: u32,
|
|
||||||
opportunities: &[DecisionOpportunity],
|
opportunities: &[DecisionOpportunity],
|
||||||
graph: &AgencyGraph,
|
graph: &AgencyGraph,
|
||||||
budget: CoverBudget,
|
budget: CoverBudget,
|
||||||
) -> Cover {
|
) -> Cover {
|
||||||
let tick = TickIndex::of(now, tick_minutes);
|
|
||||||
let active: Vec<&DecisionOpportunity> = opportunities
|
let active: Vec<&DecisionOpportunity> = opportunities
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|opportunity| opportunity.controller_mode != ControllerMode::Human)
|
.filter(|opportunity| opportunity.controller_mode != ControllerMode::Human)
|
||||||
|
|
@ -601,14 +615,28 @@ mod tests {
|
||||||
) -> Cover {
|
) -> Cover {
|
||||||
derive_cover(
|
derive_cover(
|
||||||
WorldId::nil_for_test(),
|
WorldId::nil_for_test(),
|
||||||
FictionalMinutes(tick * 60),
|
TickIndex(tick),
|
||||||
60,
|
|
||||||
opportunities,
|
opportunities,
|
||||||
graph,
|
graph,
|
||||||
budget,
|
budget,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn restriction_keeps_only_the_edges_between_the_members() {
|
||||||
|
let mut graph = AgencyGraph {
|
||||||
|
subjects: vec![subject(1), subject(2), subject(3), subject(4)],
|
||||||
|
edges: BTreeSet::new(),
|
||||||
|
};
|
||||||
|
graph.link(subject(1), subject(2));
|
||||||
|
graph.link(subject(2), subject(3));
|
||||||
|
graph.link(subject(3), subject(4));
|
||||||
|
let members = BTreeSet::from([subject(1), subject(2), subject(4)]);
|
||||||
|
let kept = graph.restricted(&members);
|
||||||
|
assert_eq!(kept.subjects, vec![subject(1), subject(2), subject(4)]);
|
||||||
|
assert_eq!(kept.edges, BTreeSet::from([(subject(1), subject(2))]));
|
||||||
|
}
|
||||||
|
|
||||||
/// Verification 21, at the design profile: 2,400 subjects, 240 cells, a cap
|
/// Verification 21, at the design profile: 2,400 subjects, 240 cells, a cap
|
||||||
/// of 24, 36 urgency slots. Every subject exactly once, the budget held, and
|
/// of 24, 36 urgency slots. Every subject exactly once, the budget held, and
|
||||||
/// the head of the attention order attended in detail.
|
/// the head of the attention order attended in detail.
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load diff
209
crates/ghostlight/src/grammar.rs
Normal file
209
crates/ghostlight/src/grammar.rs
Normal file
|
|
@ -0,0 +1,209 @@
|
||||||
|
//! The action grammar a world is bound to at creation.
|
||||||
|
//!
|
||||||
|
//! A grammar is the closed set of affordance kinds a world may declare, each
|
||||||
|
//! with its role signature and the one render path its acts take. The grammar's
|
||||||
|
//! home is the Aetheria repo; the kernel holds only this binding: the verbs it
|
||||||
|
//! enforces, and a content digest that names exactly which grammar that was.
|
||||||
|
//! The digest is derived here and nowhere else, so a binding cannot claim a
|
||||||
|
//! digest its verbs do not have.
|
||||||
|
|
||||||
|
use crate::SubjectKind;
|
||||||
|
use crate::patch::{AffordanceKindName, EntityKind, RefKind, Role, RoleSpec, kernel_speak_entry};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
/// How an act of one verb reaches the player: filmed in the engine as a ship
|
||||||
|
/// action, or shown as Aetheria's portrait-and-choices conversation.
|
||||||
|
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum RenderPath {
|
||||||
|
ShipAction,
|
||||||
|
Conversation,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a grammar role may be bound to, in the grammar's own vocabulary. Each
|
||||||
|
/// lowers to exactly one kernel `RefKind`.
|
||||||
|
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum GrammarReferentKind {
|
||||||
|
Person,
|
||||||
|
Faction,
|
||||||
|
Population,
|
||||||
|
Place,
|
||||||
|
Cargo,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GrammarReferentKind {
|
||||||
|
fn ref_kind(self) -> RefKind {
|
||||||
|
match self {
|
||||||
|
Self::Person => RefKind::Subject(Some(SubjectKind::Person)),
|
||||||
|
Self::Faction => RefKind::Subject(Some(SubjectKind::Institution)),
|
||||||
|
Self::Population => RefKind::Subject(Some(SubjectKind::Population)),
|
||||||
|
Self::Place => RefKind::Entity(EntityKind::Place),
|
||||||
|
Self::Cargo => RefKind::Entity(EntityKind::Resource),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||||
|
pub struct GrammarRole {
|
||||||
|
pub role: String,
|
||||||
|
pub referent: GrammarReferentKind,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||||
|
pub struct GrammarVerb {
|
||||||
|
pub render_path: RenderPath,
|
||||||
|
/// In signature order: the order is part of the verb.
|
||||||
|
pub roles: Vec<GrammarRole>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GrammarVerb {
|
||||||
|
/// Whether a declared role list is this verb's signature: same names, same
|
||||||
|
/// referent kinds, same order.
|
||||||
|
pub(crate) fn admits_roles(&self, roles: &[RoleSpec]) -> bool {
|
||||||
|
self.role_specs() == roles
|
||||||
|
}
|
||||||
|
|
||||||
|
/// This verb's signature as the kernel declares it: the one lowering of a
|
||||||
|
/// grammar role, so declaring a verb and admitting a declaration cannot
|
||||||
|
/// disagree.
|
||||||
|
pub(crate) fn role_specs(&self) -> Vec<RoleSpec> {
|
||||||
|
self.roles
|
||||||
|
.iter()
|
||||||
|
.map(|role| RoleSpec {
|
||||||
|
role: Role(role.role.clone()),
|
||||||
|
kind: role.referent.ref_kind(),
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why a bound grammar refuses an affordance entry.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub(crate) enum GrammarRefusal {
|
||||||
|
KindNotInGrammar,
|
||||||
|
RolesDisagree,
|
||||||
|
SpeakNotConversation,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, thiserror::Error, PartialEq, Eq)]
|
||||||
|
pub enum GrammarError {
|
||||||
|
#[error("grammar schema id is empty")]
|
||||||
|
EmptySchemaId,
|
||||||
|
#[error("grammar declares one verb kind twice")]
|
||||||
|
DuplicateVerb,
|
||||||
|
#[error("grammar digest does not match its verbs")]
|
||||||
|
DigestMismatch,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Which grammar a world is bound to: its schema id, revision and content
|
||||||
|
/// digest. What a consumer reads; the verb table stays in the binding.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct GrammarIdentity {
|
||||||
|
pub schema_id: String,
|
||||||
|
pub revision: u32,
|
||||||
|
pub digest: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The grammar a world was created under. Immutable: the only constructor
|
||||||
|
/// derives the digest, and deserialisation re-derives it and refuses a mismatch.
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||||
|
#[serde(try_from = "RawBinding")]
|
||||||
|
pub struct GrammarBinding {
|
||||||
|
schema_id: String,
|
||||||
|
revision: u32,
|
||||||
|
digest: String,
|
||||||
|
verbs: BTreeMap<String, GrammarVerb>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct RawBinding {
|
||||||
|
schema_id: String,
|
||||||
|
revision: u32,
|
||||||
|
digest: String,
|
||||||
|
verbs: BTreeMap<String, GrammarVerb>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFrom<RawBinding> for GrammarBinding {
|
||||||
|
type Error = GrammarError;
|
||||||
|
|
||||||
|
fn try_from(raw: RawBinding) -> Result<Self, GrammarError> {
|
||||||
|
let bound = Self::new(raw.schema_id, raw.revision, raw.verbs)?;
|
||||||
|
if bound.digest != raw.digest {
|
||||||
|
return Err(GrammarError::DigestMismatch);
|
||||||
|
}
|
||||||
|
Ok(bound)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GrammarBinding {
|
||||||
|
/// The one constructor. Verbs arrive in any order and are keyed by kind;
|
||||||
|
/// the digest is the sha256 of the canonical encoding of the kind-sorted
|
||||||
|
/// verbs, so the same verbs bind to the same digest however they were listed.
|
||||||
|
pub fn new(
|
||||||
|
schema_id: impl Into<String>,
|
||||||
|
revision: u32,
|
||||||
|
verbs: impl IntoIterator<Item = (String, GrammarVerb)>,
|
||||||
|
) -> Result<Self, GrammarError> {
|
||||||
|
let schema_id = schema_id.into();
|
||||||
|
if schema_id.is_empty() {
|
||||||
|
return Err(GrammarError::EmptySchemaId);
|
||||||
|
}
|
||||||
|
let mut table = BTreeMap::new();
|
||||||
|
for (kind, verb) in verbs {
|
||||||
|
if table.insert(kind, verb).is_some() {
|
||||||
|
return Err(GrammarError::DuplicateVerb);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let encoded = rmp_serde::to_vec_named(&table).expect("a verb table encodes");
|
||||||
|
let digest = format!("sha256:{:x}", Sha256::digest(encoded));
|
||||||
|
Ok(Self {
|
||||||
|
schema_id,
|
||||||
|
revision,
|
||||||
|
digest,
|
||||||
|
verbs: table,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn identity(&self) -> GrammarIdentity {
|
||||||
|
GrammarIdentity {
|
||||||
|
schema_id: self.schema_id.clone(),
|
||||||
|
revision: self.revision,
|
||||||
|
digest: self.digest.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every verb, in kind order.
|
||||||
|
pub(crate) fn verbs(&self) -> impl Iterator<Item = (&str, &GrammarVerb)> {
|
||||||
|
self.verbs.iter().map(|(kind, verb)| (kind.as_str(), verb))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn verb(&self, kind: &str) -> Option<&GrammarVerb> {
|
||||||
|
self.verbs.get(kind)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The one grammar check. The resolver turns a refusal into a mismatch and
|
||||||
|
/// `admit_resolved`, the only writer of the affordance catalog, into an
|
||||||
|
/// invariant error, so no path adds an entry without passing it.
|
||||||
|
pub(crate) fn refusal(
|
||||||
|
&self,
|
||||||
|
kind: &AffordanceKindName,
|
||||||
|
roles: &[RoleSpec],
|
||||||
|
) -> Option<GrammarRefusal> {
|
||||||
|
let Some(verb) = self.verb(&kind.0) else {
|
||||||
|
return Some(GrammarRefusal::KindNotInGrammar);
|
||||||
|
};
|
||||||
|
if !verb.admits_roles(roles) {
|
||||||
|
return Some(GrammarRefusal::RolesDisagree);
|
||||||
|
}
|
||||||
|
if *kind == kernel_speak_entry().kind && verb.render_path != RenderPath::Conversation {
|
||||||
|
return Some(GrammarRefusal::SpeakNotConversation);
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests;
|
||||||
745
crates/ghostlight/src/grammar/tests.rs
Normal file
745
crates/ghostlight/src/grammar/tests.rs
Normal file
|
|
@ -0,0 +1,745 @@
|
||||||
|
use super::*;
|
||||||
|
use crate::patch::{
|
||||||
|
AffordanceDeclaration, AffordanceKindName, AudienceSpec, Declaration, DraftHandle, EntityKind,
|
||||||
|
Mismatch, OutcomeBand, Precondition, Role, RoleSpec,
|
||||||
|
};
|
||||||
|
use crate::tests::{auth_principal, command, creation, owner};
|
||||||
|
use crate::{
|
||||||
|
CallerId, CommandBody, CommandId, CreateWorld, KernelError, SubjectKind, SubmitReceipt,
|
||||||
|
WorldId, WorldKernel, WorldPatch,
|
||||||
|
};
|
||||||
|
|
||||||
|
fn verb(path: RenderPath, roles: &[(&str, GrammarReferentKind)]) -> GrammarVerb {
|
||||||
|
GrammarVerb {
|
||||||
|
render_path: path,
|
||||||
|
roles: roles
|
||||||
|
.iter()
|
||||||
|
.map(|(role, referent)| GrammarRole {
|
||||||
|
role: (*role).into(),
|
||||||
|
referent: *referent,
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the fixture world's genesis needs: the kernel speak entry and the
|
||||||
|
/// fixture's own `convene`. Anything else a test wants is added to it.
|
||||||
|
fn grammar_with(extra: &[(&str, GrammarVerb)]) -> GrammarBinding {
|
||||||
|
let mut verbs = vec![
|
||||||
|
("speak".to_owned(), verb(RenderPath::Conversation, &[])),
|
||||||
|
("convene".to_owned(), verb(RenderPath::Conversation, &[])),
|
||||||
|
];
|
||||||
|
verbs.extend(
|
||||||
|
extra
|
||||||
|
.iter()
|
||||||
|
.map(|(kind, v)| ((*kind).to_owned(), v.clone())),
|
||||||
|
);
|
||||||
|
GrammarBinding::new("aetheria.grammar", 3, verbs).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bound(grammar: Option<GrammarBinding>, title: &str) -> CreateWorld {
|
||||||
|
let mut world = creation(CommandId::new(), title);
|
||||||
|
world.grammar = grammar;
|
||||||
|
world
|
||||||
|
}
|
||||||
|
|
||||||
|
fn declare(handle: &str, kind: &str, roles: &[(&str, RefKind)]) -> Declaration {
|
||||||
|
Declaration::Affordance(AffordanceDeclaration {
|
||||||
|
handle: DraftHandle::new(handle),
|
||||||
|
kind: AffordanceKindName(kind.into()),
|
||||||
|
roles: roles
|
||||||
|
.iter()
|
||||||
|
.map(|(role, kind)| RoleSpec {
|
||||||
|
role: Role((*role).into()),
|
||||||
|
kind: *kind,
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
// Speech with one audience is the smallest entry the resolver does
|
||||||
|
// not refuse as inert; the grammar check does not read it.
|
||||||
|
preconditions: vec![Precondition::CanBroadcast {
|
||||||
|
via: AudienceSpec::Colocated,
|
||||||
|
}],
|
||||||
|
effect_slots: Vec::new(),
|
||||||
|
outcome_bands: vec![OutcomeBand {
|
||||||
|
weight: 1,
|
||||||
|
effects: Vec::new(),
|
||||||
|
}],
|
||||||
|
carries_speech: true,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn patch_of(declarations: Vec<Declaration>) -> WorldPatch {
|
||||||
|
WorldPatch {
|
||||||
|
declarations,
|
||||||
|
operations: Vec::new(),
|
||||||
|
evidence: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rejected(result: Result<impl Sized, KernelError>) -> Vec<Mismatch> {
|
||||||
|
match result {
|
||||||
|
Err(KernelError::PatchRejected(set)) => set,
|
||||||
|
Err(other) => panic!("expected a patch refusal, got {other:?}"),
|
||||||
|
Ok(_) => panic!("expected a patch refusal, the command was admitted"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Each call gets its own store path: kernels are created, not reopened.
|
||||||
|
fn create(world: CreateWorld) -> (tempfile::TempDir, Result<WorldKernel, KernelError>) {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let result = WorldKernel::create(
|
||||||
|
directory.path().join("world.cc"),
|
||||||
|
world,
|
||||||
|
&auth_principal(owner()),
|
||||||
|
)
|
||||||
|
.map(|(kernel, _)| kernel);
|
||||||
|
(directory, result)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn admit(kernel: &mut WorldKernel, patch: WorldPatch) -> Result<SubmitReceipt, KernelError> {
|
||||||
|
let snapshot = kernel.snapshot().unwrap();
|
||||||
|
kernel.submit(
|
||||||
|
command(
|
||||||
|
&snapshot,
|
||||||
|
CommandId::new(),
|
||||||
|
CallerId::Principal(owner()),
|
||||||
|
CommandBody::AdmitPatch {
|
||||||
|
answers: None,
|
||||||
|
patch,
|
||||||
|
},
|
||||||
|
),
|
||||||
|
&auth_principal(owner()),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn person() -> RefKind {
|
||||||
|
RefKind::Subject(Some(SubjectKind::Person))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn place() -> RefKind {
|
||||||
|
RefKind::Entity(EntityKind::Place)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn not_in_grammar(handle: &str) -> Vec<Mismatch> {
|
||||||
|
vec![Mismatch::AffordanceKindNotInGrammar {
|
||||||
|
handle: DraftHandle::new(handle),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn disagrees(handle: &str) -> Vec<Mismatch> {
|
||||||
|
vec![Mismatch::AffordanceRolesDisagreeWithGrammar {
|
||||||
|
handle: DraftHandle::new(handle),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn grammar_world_refuses_an_affordance_kind_outside_the_grammar() {
|
||||||
|
// Genesis: a declared kind the binding lacks is refused.
|
||||||
|
let mut world = bound(Some(grammar_with(&[])), "Outside");
|
||||||
|
world.patch.declarations.push(declare("wave", "wave", &[]));
|
||||||
|
assert_eq!(rejected(create(world).1), not_in_grammar("wave"));
|
||||||
|
|
||||||
|
// A later AdmitPatch: the same kind is refused, and a verb the grammar
|
||||||
|
// does carry is admitted by the same path.
|
||||||
|
let extra = [("hail", verb(RenderPath::Conversation, &[]))];
|
||||||
|
let (_dir, kernel) = create(bound(Some(grammar_with(&extra)), "Outside"));
|
||||||
|
let mut kernel = kernel.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
rejected(admit(
|
||||||
|
&mut kernel,
|
||||||
|
patch_of(vec![declare("wave", "wave", &[])])
|
||||||
|
)),
|
||||||
|
not_in_grammar("wave")
|
||||||
|
);
|
||||||
|
let receipt = admit(&mut kernel, patch_of(vec![declare("hail", "hail", &[])])).unwrap();
|
||||||
|
assert!(matches!(receipt, SubmitReceipt::Applied(_)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn grammar_world_refuses_a_role_signature_the_grammar_does_not_carry() {
|
||||||
|
let extra = [
|
||||||
|
(
|
||||||
|
"meet",
|
||||||
|
verb(
|
||||||
|
RenderPath::ShipAction,
|
||||||
|
&[
|
||||||
|
("who", GrammarReferentKind::Person),
|
||||||
|
("where_", GrammarReferentKind::Place),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
("hail", verb(RenderPath::Conversation, &[])),
|
||||||
|
];
|
||||||
|
let (_dir, kernel) = create(bound(Some(grammar_with(&extra)), "Signatures"));
|
||||||
|
let mut kernel = kernel.unwrap();
|
||||||
|
for (label, roles) in [
|
||||||
|
("renamed", vec![("whom", person()), ("where_", place())]),
|
||||||
|
("rekinded", vec![("who", person()), ("where_", person())]),
|
||||||
|
("swapped", vec![("where_", place()), ("who", person())]),
|
||||||
|
("short", vec![("who", person())]),
|
||||||
|
(
|
||||||
|
"long",
|
||||||
|
vec![("who", person()), ("where_", place()), ("why", person())],
|
||||||
|
),
|
||||||
|
] {
|
||||||
|
let set = rejected(admit(
|
||||||
|
&mut kernel,
|
||||||
|
patch_of(vec![declare(label, "meet", &roles)]),
|
||||||
|
));
|
||||||
|
assert_eq!(set, disagrees(label), "{label}");
|
||||||
|
}
|
||||||
|
// A role on a verb the grammar declares with none.
|
||||||
|
let set = rejected(admit(
|
||||||
|
&mut kernel,
|
||||||
|
patch_of(vec![declare("hail", "hail", &[("who", person())])]),
|
||||||
|
));
|
||||||
|
assert_eq!(set, disagrees("hail"));
|
||||||
|
// The exact signature is admitted.
|
||||||
|
let receipt = admit(
|
||||||
|
&mut kernel,
|
||||||
|
patch_of(vec![declare(
|
||||||
|
"meet",
|
||||||
|
"meet",
|
||||||
|
&[("who", person()), ("where_", place())],
|
||||||
|
)]),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert!(matches!(receipt, SubmitReceipt::Applied(_)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn each_grammar_referent_kind_admits_exactly_its_own_kernel_kind() {
|
||||||
|
let kinds = [
|
||||||
|
(GrammarReferentKind::Person, person()),
|
||||||
|
(
|
||||||
|
GrammarReferentKind::Faction,
|
||||||
|
RefKind::Subject(Some(SubjectKind::Institution)),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
GrammarReferentKind::Population,
|
||||||
|
RefKind::Subject(Some(SubjectKind::Population)),
|
||||||
|
),
|
||||||
|
(GrammarReferentKind::Place, place()),
|
||||||
|
(
|
||||||
|
GrammarReferentKind::Cargo,
|
||||||
|
RefKind::Entity(EntityKind::Resource),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
for (referent, own) in &kinds {
|
||||||
|
let extra = [("act", verb(RenderPath::ShipAction, &[("with", *referent)]))];
|
||||||
|
for (_, offered) in &kinds {
|
||||||
|
let (_dir, kernel) = create(bound(Some(grammar_with(&extra)), "Referents"));
|
||||||
|
let mut kernel = kernel.unwrap();
|
||||||
|
let result = admit(
|
||||||
|
&mut kernel,
|
||||||
|
patch_of(vec![declare("act", "act", &[("with", *offered)])]),
|
||||||
|
);
|
||||||
|
if offered == own {
|
||||||
|
assert!(
|
||||||
|
matches!(result, Ok(SubmitReceipt::Applied(_))),
|
||||||
|
"{referent:?} refused its own kind"
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
assert_eq!(
|
||||||
|
rejected(result),
|
||||||
|
disagrees("act"),
|
||||||
|
"{referent:?} admitted {offered:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn grammar_world_without_speak_refuses_the_kernel_speak_grant() {
|
||||||
|
let no_speak = GrammarBinding::new(
|
||||||
|
"aetheria.grammar",
|
||||||
|
1,
|
||||||
|
[("convene".to_owned(), verb(RenderPath::Conversation, &[]))],
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
rejected(create(bound(Some(no_speak), "Mute")).1),
|
||||||
|
not_in_grammar(crate::patch::KERNEL_SPEAK_HANDLE)
|
||||||
|
);
|
||||||
|
|
||||||
|
// The kernel entry is held to the signature as well as the kind.
|
||||||
|
let loud = GrammarBinding::new(
|
||||||
|
"aetheria.grammar",
|
||||||
|
1,
|
||||||
|
[
|
||||||
|
(
|
||||||
|
"speak".to_owned(),
|
||||||
|
verb(
|
||||||
|
RenderPath::Conversation,
|
||||||
|
&[("to", GrammarReferentKind::Person)],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
("convene".to_owned(), verb(RenderPath::Conversation, &[])),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
rejected(create(bound(Some(loud), "Loud")).1),
|
||||||
|
disagrees(crate::patch::KERNEL_SPEAK_HANDLE)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unbound_world_keeps_the_open_catalog() {
|
||||||
|
let mut world = bound(None, "Open");
|
||||||
|
world
|
||||||
|
.patch
|
||||||
|
.declarations
|
||||||
|
.push(declare("wave", "wave", &[("at", person())]));
|
||||||
|
let (_dir, kernel) = create(world);
|
||||||
|
let mut kernel = kernel.unwrap();
|
||||||
|
let receipt = admit(
|
||||||
|
&mut kernel,
|
||||||
|
patch_of(vec![declare("beacon", "beacon", &[])]),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert!(matches!(receipt, SubmitReceipt::Applied(_)));
|
||||||
|
let snapshot = kernel.snapshot().unwrap();
|
||||||
|
assert!(snapshot.grammar.is_none());
|
||||||
|
assert!(snapshot.affordances.len() >= 4);
|
||||||
|
assert!(snapshot.affordances.iter().all(|a| a.render_path.is_none()));
|
||||||
|
|
||||||
|
// The state row of a world with no grammar carries no grammar key, so its
|
||||||
|
// bytes and digests are those of a world written before grammars existed.
|
||||||
|
let encoded = rmp_serde::to_vec_named(&kernel.state).unwrap();
|
||||||
|
let keys: std::collections::BTreeMap<String, serde::de::IgnoredAny> =
|
||||||
|
rmp_serde::from_slice(&encoded).unwrap();
|
||||||
|
assert!(!keys.contains_key("grammar"));
|
||||||
|
assert!(keys.contains_key("brief"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_bound_world_reports_its_grammar_and_derives_render_paths_from_it() {
|
||||||
|
let extra = [("dock", verb(RenderPath::ShipAction, &[]))];
|
||||||
|
let grammar = grammar_with(&extra);
|
||||||
|
let identity = grammar.identity();
|
||||||
|
let (_dir, kernel) = create(bound(Some(grammar), "Reports"));
|
||||||
|
let mut kernel = kernel.unwrap();
|
||||||
|
admit(&mut kernel, patch_of(vec![declare("dock", "dock", &[])])).unwrap();
|
||||||
|
let snapshot = kernel.snapshot().unwrap();
|
||||||
|
assert_eq!(snapshot.grammar, Some(identity));
|
||||||
|
let path_of = |kind: &str| {
|
||||||
|
snapshot
|
||||||
|
.affordances
|
||||||
|
.iter()
|
||||||
|
.find(|a| a.entry.kind.0 == kind)
|
||||||
|
.unwrap_or_else(|| panic!("{kind} is in the catalog"))
|
||||||
|
.render_path
|
||||||
|
};
|
||||||
|
assert_eq!(path_of("dock"), Some(RenderPath::ShipAction));
|
||||||
|
assert_eq!(path_of("convene"), Some(RenderPath::Conversation));
|
||||||
|
assert_eq!(path_of("speak"), Some(RenderPath::Conversation));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_reopened_grammar_world_still_holds_its_grammar() {
|
||||||
|
let grammar = grammar_with(&[]);
|
||||||
|
let identity = grammar.identity();
|
||||||
|
let (directory, kernel) = create(bound(Some(grammar), "Reopened"));
|
||||||
|
let kernel = kernel.unwrap();
|
||||||
|
let world_id = kernel.snapshot().unwrap().world_id;
|
||||||
|
drop(kernel);
|
||||||
|
let mut reopened = WorldKernel::open(directory.path().join("world.cc"), world_id).unwrap();
|
||||||
|
assert_eq!(reopened.snapshot().unwrap().grammar, Some(identity));
|
||||||
|
assert_eq!(
|
||||||
|
rejected(admit(
|
||||||
|
&mut reopened,
|
||||||
|
patch_of(vec![declare("wave", "wave", &[])])
|
||||||
|
)),
|
||||||
|
not_in_grammar("wave")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_bound_grammar_is_part_of_the_world_state_digest() {
|
||||||
|
let (_dir, kernel) = create(bound(Some(grammar_with(&[])), "Digested"));
|
||||||
|
let kernel = kernel.unwrap();
|
||||||
|
let bound_digest = crate::state_digest(&kernel.state).unwrap();
|
||||||
|
let mut state = kernel.state.clone();
|
||||||
|
state.grammar = None;
|
||||||
|
let open_digest = crate::state_digest(&state).unwrap();
|
||||||
|
state.grammar = Some(grammar_with(&[("dock", verb(RenderPath::ShipAction, &[]))]));
|
||||||
|
let other_digest = crate::state_digest(&state).unwrap();
|
||||||
|
assert_ne!(bound_digest, open_digest);
|
||||||
|
assert_ne!(bound_digest, other_digest);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn grammar_digest_is_derived_and_order_free() {
|
||||||
|
let forward = [
|
||||||
|
("alpha".to_owned(), verb(RenderPath::ShipAction, &[])),
|
||||||
|
(
|
||||||
|
"beta".to_owned(),
|
||||||
|
verb(
|
||||||
|
RenderPath::Conversation,
|
||||||
|
&[("to", GrammarReferentKind::Person)],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
("gamma".to_owned(), verb(RenderPath::Conversation, &[])),
|
||||||
|
];
|
||||||
|
let mut reversed = forward.clone();
|
||||||
|
reversed.reverse();
|
||||||
|
let a = GrammarBinding::new("aetheria.grammar", 1, forward.clone()).unwrap();
|
||||||
|
let b = GrammarBinding::new("aetheria.grammar", 1, reversed).unwrap();
|
||||||
|
assert_eq!(a.digest, b.digest);
|
||||||
|
assert_eq!(a, b);
|
||||||
|
|
||||||
|
// Content-derived: each part of a verb moves the digest.
|
||||||
|
let changed = |edit: &dyn Fn(&mut Vec<(String, GrammarVerb)>)| {
|
||||||
|
let mut verbs = forward.to_vec();
|
||||||
|
edit(&mut verbs);
|
||||||
|
GrammarBinding::new("aetheria.grammar", 1, verbs)
|
||||||
|
.unwrap()
|
||||||
|
.digest
|
||||||
|
};
|
||||||
|
assert_ne!(
|
||||||
|
a.digest,
|
||||||
|
changed(&|v| v[0].1.render_path = RenderPath::Conversation)
|
||||||
|
);
|
||||||
|
assert_ne!(a.digest, changed(&|v| v[1].1.roles[0].role = "from".into()));
|
||||||
|
assert_ne!(
|
||||||
|
a.digest,
|
||||||
|
changed(&|v| v[1].1.roles[0].referent = GrammarReferentKind::Faction)
|
||||||
|
);
|
||||||
|
assert_ne!(a.digest, changed(&|v| v[2].0 = "delta".into()));
|
||||||
|
assert_ne!(
|
||||||
|
a.digest,
|
||||||
|
changed(&|v| {
|
||||||
|
v.pop();
|
||||||
|
})
|
||||||
|
);
|
||||||
|
// Role order is part of a verb.
|
||||||
|
let ordered = |roles: &[(&str, GrammarReferentKind)]| {
|
||||||
|
GrammarBinding::new(
|
||||||
|
"g",
|
||||||
|
1,
|
||||||
|
[("meet".to_owned(), verb(RenderPath::ShipAction, roles))],
|
||||||
|
)
|
||||||
|
.unwrap()
|
||||||
|
.digest
|
||||||
|
};
|
||||||
|
assert_ne!(
|
||||||
|
ordered(&[
|
||||||
|
("a", GrammarReferentKind::Person),
|
||||||
|
("b", GrammarReferentKind::Place)
|
||||||
|
]),
|
||||||
|
ordered(&[
|
||||||
|
("b", GrammarReferentKind::Place),
|
||||||
|
("a", GrammarReferentKind::Person)
|
||||||
|
])
|
||||||
|
);
|
||||||
|
// The identity reads the same fields back.
|
||||||
|
let identity = a.identity();
|
||||||
|
assert_eq!(identity.schema_id, "aetheria.grammar");
|
||||||
|
assert_eq!(identity.revision, 1);
|
||||||
|
assert_eq!(identity.digest, a.digest);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_tampered_grammar_digest_fails_to_deserialise() {
|
||||||
|
let binding = grammar_with(&[]);
|
||||||
|
let value = serde_json::to_value(&binding).unwrap();
|
||||||
|
// Untouched: the round trip holds.
|
||||||
|
let back: GrammarBinding = serde_json::from_value(value.clone()).unwrap();
|
||||||
|
assert_eq!(back, binding);
|
||||||
|
|
||||||
|
// A digest the verbs do not have.
|
||||||
|
let mut forged = value.clone();
|
||||||
|
forged["digest"] = "sha256:00".into();
|
||||||
|
assert!(serde_json::from_value::<GrammarBinding>(forged.clone()).is_err());
|
||||||
|
|
||||||
|
// A verb edited under the digest it already had.
|
||||||
|
let mut edited = value;
|
||||||
|
edited["verbs"]["convene"]["render_path"] = "ship_action".into();
|
||||||
|
assert!(serde_json::from_value::<GrammarBinding>(edited).is_err());
|
||||||
|
|
||||||
|
// The named encoding a state row uses refuses it the same way.
|
||||||
|
let bytes = rmp_serde::to_vec_named(&forged).unwrap();
|
||||||
|
assert!(rmp_serde::from_slice::<GrammarBinding>(&bytes).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_grammar_names_each_verb_once_and_has_a_schema() {
|
||||||
|
assert_eq!(
|
||||||
|
GrammarBinding::new("", 1, Vec::new()).unwrap_err(),
|
||||||
|
GrammarError::EmptySchemaId
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
GrammarBinding::new(
|
||||||
|
"g",
|
||||||
|
1,
|
||||||
|
[
|
||||||
|
("hail".to_owned(), verb(RenderPath::Conversation, &[])),
|
||||||
|
("hail".to_owned(), verb(RenderPath::ShipAction, &[])),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
.unwrap_err(),
|
||||||
|
GrammarError::DuplicateVerb
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The fixture world was written by the code at base 367e2eb, which has no
|
||||||
|
/// grammar field anywhere. Reopening it must reproduce the digests that code
|
||||||
|
/// recorded.
|
||||||
|
#[test]
|
||||||
|
fn existing_world_reopens_with_unchanged_digests() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let path = directory.path().join("world.cc");
|
||||||
|
std::fs::write(&path, include_bytes!("../../tests/fixtures/base_world.cc")).unwrap();
|
||||||
|
let world_id: WorldId =
|
||||||
|
serde_json::from_str(include_str!("../../tests/fixtures/base_world.id").trim()).unwrap();
|
||||||
|
let kernel = WorldKernel::open(&path, world_id).expect("a base-written world reopens");
|
||||||
|
let snapshot = kernel.snapshot().unwrap();
|
||||||
|
let recorded = include_str!("../../tests/fixtures/base_world.digests");
|
||||||
|
let mut lines = recorded.lines();
|
||||||
|
assert_eq!(snapshot.revision.to_string(), lines.next().unwrap());
|
||||||
|
assert_eq!(snapshot.state_digest, lines.next().unwrap());
|
||||||
|
assert_eq!(
|
||||||
|
snapshot.last_commit_digest.as_deref(),
|
||||||
|
Some(lines.next().unwrap())
|
||||||
|
);
|
||||||
|
assert!(snapshot.grammar.is_none());
|
||||||
|
// Its state still derives the recorded digest from its bytes.
|
||||||
|
assert_eq!(
|
||||||
|
crate::state_digest(&kernel.state).unwrap(),
|
||||||
|
snapshot.state_digest
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn submit_as(
|
||||||
|
kernel: &mut WorldKernel,
|
||||||
|
caller: CallerId,
|
||||||
|
answers: Option<crate::PatchAnswer>,
|
||||||
|
patch: WorldPatch,
|
||||||
|
) -> Result<SubmitReceipt, KernelError> {
|
||||||
|
let snapshot = kernel.snapshot().unwrap();
|
||||||
|
kernel.submit(
|
||||||
|
command(
|
||||||
|
&snapshot,
|
||||||
|
CommandId::new(),
|
||||||
|
caller.clone(),
|
||||||
|
CommandBody::AdmitPatch { answers, patch },
|
||||||
|
),
|
||||||
|
&crate::AuthenticatedCaller::fixture(caller),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A bound Draft world whose revision has moved past genesis: one owner patch
|
||||||
|
/// that adds a dead-end place the elaborator can answer.
|
||||||
|
fn advanced_grammar_world() -> (tempfile::TempDir, WorldKernel, crate::EntityId) {
|
||||||
|
let extra = [("hail", verb(RenderPath::Conversation, &[]))];
|
||||||
|
let (dir, kernel) = create(bound(Some(grammar_with(&extra)), "Advanced"));
|
||||||
|
let mut kernel = kernel.unwrap();
|
||||||
|
let commons = *kernel.state.entities.keys().next().unwrap();
|
||||||
|
admit(
|
||||||
|
&mut kernel,
|
||||||
|
patch_of(vec![
|
||||||
|
Declaration::Entity(crate::patch::EntityDeclaration {
|
||||||
|
handle: DraftHandle::new("dead-end"),
|
||||||
|
label: "The Unwalked Road".into(),
|
||||||
|
kind: EntityKind::Place,
|
||||||
|
container: None,
|
||||||
|
}),
|
||||||
|
Declaration::Route(crate::patch::RouteDeclaration {
|
||||||
|
handle: DraftHandle::new("gate"),
|
||||||
|
label: "The Field Gate".into(),
|
||||||
|
from: crate::patch::Ref::Existing(commons),
|
||||||
|
to: crate::patch::Ref::Draft(DraftHandle::new("dead-end")),
|
||||||
|
access: crate::patch::AccessKind::Public,
|
||||||
|
cost: crate::patch::Cost(1),
|
||||||
|
}),
|
||||||
|
]),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let dead_end = *kernel
|
||||||
|
.state
|
||||||
|
.entities
|
||||||
|
.iter()
|
||||||
|
.find(|(_, record)| record.label == "The Unwalked Road")
|
||||||
|
.map(|(id, _)| id)
|
||||||
|
.unwrap();
|
||||||
|
(dir, kernel, dead_end)
|
||||||
|
}
|
||||||
|
|
||||||
|
type Door = (&'static str, CallerId, Option<crate::PatchAnswer>);
|
||||||
|
|
||||||
|
/// Each door refuses an outside kind and a wrong role signature, typed, and the
|
||||||
|
/// refusal leaves the revision where it was. The owner and the consumer declare
|
||||||
|
/// unanswered only in Draft; Play and the elaborator act in Active.
|
||||||
|
fn refuse_at_each_door(kernel: &mut WorldKernel, doors: Vec<Door>) {
|
||||||
|
for (door, caller, answers) in doors {
|
||||||
|
let revision = kernel.state.revision;
|
||||||
|
let kind = submit_as(
|
||||||
|
kernel,
|
||||||
|
caller.clone(),
|
||||||
|
answers.clone(),
|
||||||
|
patch_of(vec![declare("wave", "wave", &[])]),
|
||||||
|
);
|
||||||
|
assert_eq!(rejected(kind), not_in_grammar("wave"), "{door}");
|
||||||
|
let roles = submit_as(
|
||||||
|
kernel,
|
||||||
|
caller,
|
||||||
|
answers,
|
||||||
|
patch_of(vec![declare("hail", "hail", &[("who", person())])]),
|
||||||
|
);
|
||||||
|
assert_eq!(rejected(roles), disagrees("hail"), "{door}");
|
||||||
|
assert_eq!(
|
||||||
|
kernel.state.revision, revision,
|
||||||
|
"{door} refusal moved the world"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_admission_door_refuses_outside_the_grammar_after_the_revision_has_moved() {
|
||||||
|
let (_dir, mut kernel, dead_end) = advanced_grammar_world();
|
||||||
|
assert_eq!(kernel.state.revision, 1);
|
||||||
|
let draft_doors = vec![
|
||||||
|
("owner", CallerId::Principal(owner()), None),
|
||||||
|
(
|
||||||
|
"consumer",
|
||||||
|
CallerId::System(crate::SystemCapability::Consumer {
|
||||||
|
consumer: crate::ConsumerId::of_name("grammar-door"),
|
||||||
|
}),
|
||||||
|
None,
|
||||||
|
),
|
||||||
|
];
|
||||||
|
refuse_at_each_door(&mut kernel, draft_doors);
|
||||||
|
crate::tests::activate(&mut kernel);
|
||||||
|
assert!(
|
||||||
|
kernel.state.revision > 1,
|
||||||
|
"the world has moved past genesis"
|
||||||
|
);
|
||||||
|
let answer = crate::derive_boundaries(&kernel.state)
|
||||||
|
.unwrap()
|
||||||
|
.into_iter()
|
||||||
|
.find(|boundary| {
|
||||||
|
matches!(boundary, crate::CausalBoundary::UnelaboratedDestination { place, .. }
|
||||||
|
if *place == dead_end)
|
||||||
|
})
|
||||||
|
.expect("the dead end is an unelaborated destination");
|
||||||
|
let active_doors = vec![
|
||||||
|
(
|
||||||
|
"play",
|
||||||
|
CallerId::System(crate::SystemCapability::Play),
|
||||||
|
None,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"elaborator",
|
||||||
|
CallerId::System(crate::SystemCapability::Elaborator {
|
||||||
|
jurisdiction: crate::JurisdictionKey::PlaceSubtree(dead_end),
|
||||||
|
}),
|
||||||
|
Some(crate::PatchAnswer::Boundary(answer)),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
refuse_at_each_door(&mut kernel, active_doors);
|
||||||
|
// The same path admits what the grammar carries, so the refusals above are
|
||||||
|
// the grammar's and not a closed door.
|
||||||
|
let receipt = submit_as(
|
||||||
|
&mut kernel,
|
||||||
|
CallerId::System(crate::SystemCapability::Play),
|
||||||
|
None,
|
||||||
|
patch_of(vec![declare("hail", "hail", &[])]),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert!(matches!(receipt, SubmitReceipt::Applied(_)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_grammar_that_binds_speak_as_anything_but_conversation_is_refused_at_bind() {
|
||||||
|
let ship = |roles: &[(&str, GrammarReferentKind)]| {
|
||||||
|
GrammarBinding::new(
|
||||||
|
"aetheria.grammar",
|
||||||
|
1,
|
||||||
|
[
|
||||||
|
("speak".to_owned(), verb(RenderPath::ShipAction, roles)),
|
||||||
|
("convene".to_owned(), verb(RenderPath::Conversation, &[])),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.unwrap()
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
rejected(create(bound(Some(ship(&[])), "Filmed speech")).1),
|
||||||
|
vec![Mismatch::SpeakRenderPathDisagreesWithGrammar {
|
||||||
|
handle: DraftHandle::new(crate::patch::KERNEL_SPEAK_HANDLE),
|
||||||
|
}]
|
||||||
|
);
|
||||||
|
// A ShipAction speak with a role fails on the signature first and is still
|
||||||
|
// refused: no variant of speak but zero roles, Conversation, is admitted.
|
||||||
|
assert_eq!(
|
||||||
|
rejected(
|
||||||
|
create(bound(
|
||||||
|
Some(ship(&[("to", GrammarReferentKind::Person)])),
|
||||||
|
"Loud"
|
||||||
|
))
|
||||||
|
.1
|
||||||
|
),
|
||||||
|
disagrees(crate::patch::KERNEL_SPEAK_HANDLE)
|
||||||
|
);
|
||||||
|
// The control: Conversation speak binds.
|
||||||
|
assert!(create(bound(Some(grammar_with(&[])), "Spoken")).1.is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `apply_effect` re-decides an effect it is handed. An effect resolved against
|
||||||
|
/// a world with no grammar must not install an entry the bound grammar lacks:
|
||||||
|
/// the catalog's only writer holds the grammar check itself.
|
||||||
|
#[test]
|
||||||
|
fn an_effect_resolved_elsewhere_cannot_install_an_entry_outside_the_grammar() {
|
||||||
|
let extra = [
|
||||||
|
(
|
||||||
|
"meet",
|
||||||
|
verb(
|
||||||
|
RenderPath::ShipAction,
|
||||||
|
&[("who", GrammarReferentKind::Person)],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
("hail", verb(RenderPath::Conversation, &[])),
|
||||||
|
];
|
||||||
|
let (_dir, kernel) = create(bound(Some(grammar_with(&extra)), "Forged"));
|
||||||
|
let kernel = kernel.unwrap();
|
||||||
|
let mut twin = kernel.state.clone();
|
||||||
|
twin.grammar = None;
|
||||||
|
let resolve = |kind: &str, roles: &[(&str, RefKind)]| {
|
||||||
|
crate::patch::resolve_patch(
|
||||||
|
&twin,
|
||||||
|
CommandId::new(),
|
||||||
|
&patch_of(vec![declare("probe", kind, roles)]),
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.expect("the unbound twin admits any canonical kind")
|
||||||
|
};
|
||||||
|
for (label, resolved, admitted) in [
|
||||||
|
("outside kind", resolve("wave", &[]), false),
|
||||||
|
("wrong roles", resolve("meet", &[("whom", person())]), false),
|
||||||
|
("carried verb", resolve("hail", &[]), true),
|
||||||
|
] {
|
||||||
|
let mut state = kernel.state.clone();
|
||||||
|
let catalog = state.affordance_catalog.len();
|
||||||
|
let result = crate::apply_effect(
|
||||||
|
&mut state,
|
||||||
|
CommandId::new(),
|
||||||
|
&CallerId::Principal(owner()),
|
||||||
|
&crate::WorldEffect::PatchAdmitted {
|
||||||
|
answers: None,
|
||||||
|
resolved,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if admitted {
|
||||||
|
result.unwrap_or_else(|error| panic!("{label}: {error:?}"));
|
||||||
|
assert_eq!(state.affordance_catalog.len(), catalog + 1, "{label}");
|
||||||
|
} else {
|
||||||
|
assert!(
|
||||||
|
matches!(result, Err(KernelError::Invariant(_))),
|
||||||
|
"{label}: {result:?}"
|
||||||
|
);
|
||||||
|
assert_eq!(state.affordance_catalog.len(), catalog, "{label}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
765
crates/ghostlight/src/hierarchy.rs
Normal file
765
crates/ghostlight/src/hierarchy.rs
Normal file
|
|
@ -0,0 +1,765 @@
|
||||||
|
//! The gestalt hierarchy: who hangs from whom, derived from world state on
|
||||||
|
//! every read.
|
||||||
|
//!
|
||||||
|
//! This organ owns the tree and nothing else. [`derive_hierarchy`] is pure over
|
||||||
|
//! a `&WorldState`: no clock, no entropy, no mailbox, no filesystem. Nothing it
|
||||||
|
//! returns is stored, cached or admitted; a node, a [`NodeId`] and a home
|
||||||
|
//! parent change only because the world changed through an ordinary command
|
||||||
|
//! (an office granted, an authority granted, a subject moved).
|
||||||
|
//!
|
||||||
|
//! Like the agency graph it is wider than any subject view, so it is reachable
|
||||||
|
//! from `WorldMailbox` and from neither `ControllerPort` nor `ElaborationPort`.
|
||||||
|
//! The agency graph stays the adjacency inside one node.
|
||||||
|
//!
|
||||||
|
//! Home-parent rule, the first that exists: the institution in which the
|
||||||
|
//! subject holds an office (several: fewest live members, then lowest id); the
|
||||||
|
//! institution holding an authority grant over the subject (several: lowest
|
||||||
|
//! id); the innermost institution holding a grant over a place subtree that
|
||||||
|
//! contains its position (several over one place: lowest id); the place node
|
||||||
|
//! of its own position; the root. A subject never hangs from itself. Two
|
||||||
|
//! institutions that would hang from each other are a cycle, broken at its
|
||||||
|
//! lowest id, which hangs from the root. Other ties stay context, not a second
|
||||||
|
//! parent: one home per subject.
|
||||||
|
|
||||||
|
use super::{
|
||||||
|
ControllerMode, EntityId, EntityKind, FictionalMinutes, SubjectId, SubjectKind, WorldId,
|
||||||
|
WorldState, cover::derive_uuid, patch::AuthorityTarget,
|
||||||
|
};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
/// Fixed, never regenerated: two worlds in one process are separated by the
|
||||||
|
/// world id inside the name, as cover ids are.
|
||||||
|
const NODE_NAMESPACE: &str = "ghostlight.gestalt.node.v1";
|
||||||
|
|
||||||
|
/// Derived from `(world, anchor)`, so the same anchor in the same world is the
|
||||||
|
/// same node on every read and across every unrelated commit.
|
||||||
|
#[derive(
|
||||||
|
Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
|
||||||
|
)]
|
||||||
|
#[serde(transparent)]
|
||||||
|
pub struct NodeId(Uuid);
|
||||||
|
|
||||||
|
impl NodeId {
|
||||||
|
pub(crate) fn of(world: WorldId, anchor: &NodeAnchor) -> Self {
|
||||||
|
Self(derive_uuid(
|
||||||
|
NODE_NAMESPACE,
|
||||||
|
&format!("node|{world:?}|{anchor:?}"),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a node stands on. `Subject` names a leaf: a derived hierarchy lists
|
||||||
|
/// leaves as a node's `loose` subjects and mints no node for them, so the
|
||||||
|
/// variant exists to give a leaf one stable id when a planner needs it.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||||
|
#[serde(tag = "anchor", content = "id", rename_all = "snake_case")]
|
||||||
|
pub enum NodeAnchor {
|
||||||
|
World,
|
||||||
|
Institution(SubjectId),
|
||||||
|
Place(EntityId),
|
||||||
|
Subject(SubjectId),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct Node {
|
||||||
|
pub id: NodeId,
|
||||||
|
pub anchor: NodeAnchor,
|
||||||
|
/// `None` for the root alone.
|
||||||
|
pub parent: Option<NodeId>,
|
||||||
|
/// Ascending by id.
|
||||||
|
pub children: Vec<NodeId>,
|
||||||
|
/// The institution subject that speaks for its own node, when it has a
|
||||||
|
/// non-Human controller. `None` for the root and for place nodes.
|
||||||
|
pub voice: Option<SubjectId>,
|
||||||
|
/// Subjects that hang directly from this node and are not nodes
|
||||||
|
/// themselves. Ascending. Never the Human subject.
|
||||||
|
pub loose: Vec<SubjectId>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct Hierarchy {
|
||||||
|
root: NodeId,
|
||||||
|
pub nodes: BTreeMap<NodeId, Node>,
|
||||||
|
/// Every placed subject's one parent node, the Human subject included:
|
||||||
|
/// the player is placed, never a voice.
|
||||||
|
pub home: BTreeMap<SubjectId, NodeId>,
|
||||||
|
/// When each voice last consumed a decision opportunity; absent means
|
||||||
|
/// never. Read from the kernel's `last_opportunity_at`.
|
||||||
|
pub last_attended: BTreeMap<SubjectId, FictionalMinutes>,
|
||||||
|
/// The voices that are populations. A closed place node still speaks for
|
||||||
|
/// its populations; its persons are silent.
|
||||||
|
pub populations: BTreeSet<SubjectId>,
|
||||||
|
/// For every place, the node that governs it: its own place node if one
|
||||||
|
/// exists, else its innermost governing institution, else the nearest
|
||||||
|
/// enclosing place node, else the root.
|
||||||
|
governing: BTreeMap<EntityId, NodeId>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Hierarchy {
|
||||||
|
pub fn root(&self) -> NodeId {
|
||||||
|
self.root
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The chain of nodes that govern `place`, innermost first and ending at
|
||||||
|
/// the root. A place the world does not hold is governed by the root
|
||||||
|
/// alone.
|
||||||
|
pub fn focus_path(&self, place: EntityId) -> Vec<NodeId> {
|
||||||
|
let mut path = Vec::new();
|
||||||
|
let mut current = Some(self.governing.get(&place).copied().unwrap_or(self.root));
|
||||||
|
while let Some(id) = current {
|
||||||
|
path.push(id);
|
||||||
|
current = self.nodes.get(&id).and_then(|node| node.parent);
|
||||||
|
}
|
||||||
|
path
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
enum Home {
|
||||||
|
Institution(SubjectId),
|
||||||
|
Place(EntityId),
|
||||||
|
Root,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The place and its containers, innermost first. Bounded by the entity count,
|
||||||
|
/// so a corrupt containment loop cannot spin.
|
||||||
|
fn place_chain(state: &WorldState, place: EntityId) -> Vec<EntityId> {
|
||||||
|
let mut chain = Vec::new();
|
||||||
|
let mut current = Some(place);
|
||||||
|
for _ in 0..=state.entities.len() {
|
||||||
|
let Some(node) = current else { break };
|
||||||
|
chain.push(node);
|
||||||
|
current = state
|
||||||
|
.entities
|
||||||
|
.get(&node)
|
||||||
|
.and_then(|record| record.container);
|
||||||
|
}
|
||||||
|
chain
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn derive_hierarchy(state: &WorldState) -> Hierarchy {
|
||||||
|
// Who exists to the hierarchy: every subject with a controller. Voices are
|
||||||
|
// the ones that are not Human.
|
||||||
|
let mut placed: BTreeSet<SubjectId> = BTreeSet::new();
|
||||||
|
let mut voices: BTreeSet<SubjectId> = BTreeSet::new();
|
||||||
|
for (scope, controller) in &state.controller_assignments {
|
||||||
|
match controller.mode() {
|
||||||
|
Some(ControllerMode::Human) => {
|
||||||
|
placed.insert(scope.subject_id);
|
||||||
|
}
|
||||||
|
Some(_) => {
|
||||||
|
placed.insert(scope.subject_id);
|
||||||
|
voices.insert(scope.subject_id);
|
||||||
|
}
|
||||||
|
None => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let institutions: BTreeSet<SubjectId> = voices
|
||||||
|
.iter()
|
||||||
|
.copied()
|
||||||
|
.filter(|subject| {
|
||||||
|
state
|
||||||
|
.subjects
|
||||||
|
.get(subject)
|
||||||
|
.is_some_and(|record| record.kind == SubjectKind::Institution)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
// Office incumbency: subject -> (institution, its live member count).
|
||||||
|
let members = |institution: SubjectId| -> usize {
|
||||||
|
state
|
||||||
|
.selection
|
||||||
|
.get(&institution)
|
||||||
|
.map(|offices| {
|
||||||
|
offices
|
||||||
|
.values()
|
||||||
|
.filter_map(|office| office.incumbent)
|
||||||
|
.filter(|incumbent| placed.contains(incumbent))
|
||||||
|
.collect::<BTreeSet<_>>()
|
||||||
|
.len()
|
||||||
|
})
|
||||||
|
.unwrap_or(0)
|
||||||
|
};
|
||||||
|
let mut offices_held: BTreeMap<SubjectId, Vec<SubjectId>> = BTreeMap::new();
|
||||||
|
for institution in &institutions {
|
||||||
|
for office in state.selection.get(institution).into_iter().flat_map(|o| o.values()) {
|
||||||
|
if let Some(incumbent) = office.incumbent
|
||||||
|
&& placed.contains(&incumbent)
|
||||||
|
{
|
||||||
|
let held = offices_held.entry(incumbent).or_default();
|
||||||
|
if !held.contains(institution) {
|
||||||
|
held.push(*institution);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Authority grants held by an institution, by what they cover.
|
||||||
|
let mut over_subject: BTreeMap<SubjectId, BTreeSet<SubjectId>> = BTreeMap::new();
|
||||||
|
let mut over_place: BTreeMap<EntityId, BTreeSet<SubjectId>> = BTreeMap::new();
|
||||||
|
for (holder, grants) in &state.authority {
|
||||||
|
if !institutions.contains(holder) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for grant in grants {
|
||||||
|
match grant.over {
|
||||||
|
AuthorityTarget::Subject(subject) => {
|
||||||
|
over_subject.entry(subject).or_default().insert(*holder);
|
||||||
|
}
|
||||||
|
AuthorityTarget::PlaceSubtree(place) => {
|
||||||
|
over_place.entry(place).or_default().insert(*holder);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut home_of: BTreeMap<SubjectId, Home> = BTreeMap::new();
|
||||||
|
for subject in &placed {
|
||||||
|
let own = *subject;
|
||||||
|
let by_office = offices_held.get(&own).and_then(|held| {
|
||||||
|
held.iter()
|
||||||
|
.copied()
|
||||||
|
.filter(|institution| *institution != own)
|
||||||
|
.min_by_key(|institution| (members(*institution), *institution))
|
||||||
|
});
|
||||||
|
let by_grant = || {
|
||||||
|
over_subject
|
||||||
|
.get(&own)
|
||||||
|
.and_then(|holders| holders.iter().copied().find(|holder| *holder != own))
|
||||||
|
};
|
||||||
|
let by_place = || {
|
||||||
|
let position = state.positions.get(&own)?;
|
||||||
|
place_chain(state, position.place).into_iter().find_map(|place| {
|
||||||
|
over_place
|
||||||
|
.get(&place)
|
||||||
|
.and_then(|holders| holders.iter().copied().find(|holder| *holder != own))
|
||||||
|
})
|
||||||
|
};
|
||||||
|
let home = by_office
|
||||||
|
.or_else(by_grant)
|
||||||
|
.or_else(by_place)
|
||||||
|
.map(Home::Institution)
|
||||||
|
.or_else(|| state.positions.get(&own).map(|position| Home::Place(position.place)))
|
||||||
|
.unwrap_or(Home::Root);
|
||||||
|
home_of.insert(own, home);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A cycle can only run through institutions. Break each at its lowest id.
|
||||||
|
let mut settled: BTreeSet<SubjectId> = BTreeSet::new();
|
||||||
|
for start in &institutions {
|
||||||
|
let mut path: Vec<SubjectId> = Vec::new();
|
||||||
|
let mut current = *start;
|
||||||
|
loop {
|
||||||
|
if settled.contains(¤t) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if let Some(at) = path.iter().position(|seen| *seen == current) {
|
||||||
|
let lowest = path[at..].iter().copied().min().expect("a cycle is non-empty");
|
||||||
|
home_of.insert(lowest, Home::Root);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
path.push(current);
|
||||||
|
match home_of.get(¤t) {
|
||||||
|
Some(Home::Institution(parent)) => current = *parent,
|
||||||
|
_ => break,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
settled.extend(path);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Place nodes exist only where some subject hangs from one.
|
||||||
|
let place_nodes: BTreeSet<EntityId> = home_of
|
||||||
|
.values()
|
||||||
|
.filter_map(|home| match home {
|
||||||
|
Home::Place(place) => Some(*place),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let world = state.world_id;
|
||||||
|
let root = NodeId::of(world, &NodeAnchor::World);
|
||||||
|
let institution_node = |institution: SubjectId| NodeId::of(world, &NodeAnchor::Institution(institution));
|
||||||
|
let place_node = |place: EntityId| NodeId::of(world, &NodeAnchor::Place(place));
|
||||||
|
let node_of_home = |home: &Home| match home {
|
||||||
|
Home::Institution(institution) => institution_node(*institution),
|
||||||
|
Home::Place(place) => place_node(*place),
|
||||||
|
Home::Root => root,
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut nodes: BTreeMap<NodeId, Node> = BTreeMap::new();
|
||||||
|
nodes.insert(
|
||||||
|
root,
|
||||||
|
Node {
|
||||||
|
id: root,
|
||||||
|
anchor: NodeAnchor::World,
|
||||||
|
parent: None,
|
||||||
|
children: Vec::new(),
|
||||||
|
voice: None,
|
||||||
|
loose: Vec::new(),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
for institution in &institutions {
|
||||||
|
let id = institution_node(*institution);
|
||||||
|
nodes.insert(
|
||||||
|
id,
|
||||||
|
Node {
|
||||||
|
id,
|
||||||
|
anchor: NodeAnchor::Institution(*institution),
|
||||||
|
parent: Some(node_of_home(&home_of[institution])),
|
||||||
|
children: Vec::new(),
|
||||||
|
voice: Some(*institution),
|
||||||
|
loose: Vec::new(),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for place in &place_nodes {
|
||||||
|
let id = place_node(*place);
|
||||||
|
let parent = place_chain(state, *place)
|
||||||
|
.into_iter()
|
||||||
|
.skip(1)
|
||||||
|
.find(|ancestor| place_nodes.contains(ancestor))
|
||||||
|
.map(place_node)
|
||||||
|
.unwrap_or(root);
|
||||||
|
nodes.insert(
|
||||||
|
id,
|
||||||
|
Node {
|
||||||
|
id,
|
||||||
|
anchor: NodeAnchor::Place(*place),
|
||||||
|
parent: Some(parent),
|
||||||
|
children: Vec::new(),
|
||||||
|
voice: None,
|
||||||
|
loose: Vec::new(),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut home: BTreeMap<SubjectId, NodeId> = BTreeMap::new();
|
||||||
|
for (subject, subject_home) in &home_of {
|
||||||
|
let parent = node_of_home(subject_home);
|
||||||
|
home.insert(*subject, parent);
|
||||||
|
if voices.contains(subject) && !institutions.contains(subject) {
|
||||||
|
nodes
|
||||||
|
.get_mut(&parent)
|
||||||
|
.expect("a home names a node that was just minted")
|
||||||
|
.loose
|
||||||
|
.push(*subject);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let links: Vec<(NodeId, NodeId)> = nodes
|
||||||
|
.values()
|
||||||
|
.filter_map(|node| node.parent.map(|parent| (parent, node.id)))
|
||||||
|
.collect();
|
||||||
|
for (parent, child) in links {
|
||||||
|
nodes
|
||||||
|
.get_mut(&parent)
|
||||||
|
.expect("a parent is a minted node")
|
||||||
|
.children
|
||||||
|
.push(child);
|
||||||
|
}
|
||||||
|
// `home_of` iterates ascending, so `loose` is already ascending; children
|
||||||
|
// arrive in node-id order from `nodes`.
|
||||||
|
|
||||||
|
let mut governing: BTreeMap<EntityId, NodeId> = BTreeMap::new();
|
||||||
|
for (place, record) in &state.entities {
|
||||||
|
if record.kind != EntityKind::Place {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let chain = place_chain(state, *place);
|
||||||
|
let node = if place_nodes.contains(place) {
|
||||||
|
place_node(*place)
|
||||||
|
} else if let Some(holder) = chain
|
||||||
|
.iter()
|
||||||
|
.find_map(|link| over_place.get(link).and_then(|holders| holders.first()))
|
||||||
|
{
|
||||||
|
institution_node(*holder)
|
||||||
|
} else {
|
||||||
|
chain
|
||||||
|
.iter()
|
||||||
|
.find(|link| place_nodes.contains(link))
|
||||||
|
.map(|link| place_node(*link))
|
||||||
|
.unwrap_or(root)
|
||||||
|
};
|
||||||
|
governing.insert(*place, node);
|
||||||
|
}
|
||||||
|
|
||||||
|
let last_attended = voices
|
||||||
|
.iter()
|
||||||
|
.filter_map(|voice| {
|
||||||
|
state
|
||||||
|
.last_opportunity_at
|
||||||
|
.get(voice)
|
||||||
|
.map(|at| (*voice, *at))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let populations = voices
|
||||||
|
.iter()
|
||||||
|
.copied()
|
||||||
|
.filter(|voice| {
|
||||||
|
state
|
||||||
|
.subjects
|
||||||
|
.get(voice)
|
||||||
|
.is_some_and(|record| record.kind == SubjectKind::Population)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
Hierarchy {
|
||||||
|
root,
|
||||||
|
nodes,
|
||||||
|
home,
|
||||||
|
last_attended,
|
||||||
|
populations,
|
||||||
|
governing,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
pub(crate) mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::patch::{
|
||||||
|
AuthorityGrant, AuthorityKindName, EntityRecord, Office, OfficeName, Position,
|
||||||
|
};
|
||||||
|
use crate::{
|
||||||
|
ControllerAssignment, ControllerId, DecisionScope, PrincipalId, SubjectState,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub(crate) struct Fixture {
|
||||||
|
pub(crate) state: WorldState,
|
||||||
|
next: u128,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Fixture {
|
||||||
|
pub(crate) fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
state: WorldState::empty(
|
||||||
|
WorldId(Uuid::from_u128(0xfeed)),
|
||||||
|
PrincipalId::new("owner"),
|
||||||
|
"Hierarchy".into(),
|
||||||
|
None,
|
||||||
|
),
|
||||||
|
next: 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn uuid(&mut self) -> Uuid {
|
||||||
|
self.next += 1;
|
||||||
|
Uuid::from_u128(self.next)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn place(&mut self, label: &str, container: Option<EntityId>) -> EntityId {
|
||||||
|
let id = EntityId(self.uuid());
|
||||||
|
self.state.entities.insert(
|
||||||
|
id,
|
||||||
|
EntityRecord {
|
||||||
|
label: label.into(),
|
||||||
|
kind: EntityKind::Place,
|
||||||
|
container,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
id
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn subject(&mut self, label: &str, kind: SubjectKind, at: Option<EntityId>) -> SubjectId {
|
||||||
|
let id = SubjectId(self.uuid());
|
||||||
|
let controller_id = ControllerId(self.uuid());
|
||||||
|
self.state.subjects.insert(
|
||||||
|
id,
|
||||||
|
SubjectState {
|
||||||
|
label: label.into(),
|
||||||
|
kind,
|
||||||
|
import_key: None,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
self.state.controller_assignments.insert(
|
||||||
|
DecisionScope { subject_id: id },
|
||||||
|
ControllerAssignment::NarrativePersona { controller_id },
|
||||||
|
);
|
||||||
|
if let Some(place) = at {
|
||||||
|
self.state.positions.insert(id, Position { place });
|
||||||
|
}
|
||||||
|
id
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn player(&mut self, at: EntityId) -> SubjectId {
|
||||||
|
let id = self.subject("Player", SubjectKind::Person, Some(at));
|
||||||
|
let controller_id = ControllerId(self.uuid());
|
||||||
|
self.state.controller_assignments.insert(
|
||||||
|
DecisionScope { subject_id: id },
|
||||||
|
ControllerAssignment::Human {
|
||||||
|
controller_id,
|
||||||
|
principal: PrincipalId::new("player"),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
id
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn office(&mut self, institution: SubjectId, name: &str, incumbent: SubjectId) {
|
||||||
|
self.state.selection.entry(institution).or_default().insert(
|
||||||
|
OfficeName(name.into()),
|
||||||
|
Office {
|
||||||
|
incumbent: Some(incumbent),
|
||||||
|
delegated: [AuthorityKindName("rule".into())].into(),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn grant(&mut self, holder: SubjectId, over: AuthorityTarget) {
|
||||||
|
self.state.authority.entry(holder).or_default().insert(AuthorityGrant {
|
||||||
|
kind: AuthorityKindName("rule".into()),
|
||||||
|
over,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parent_of(hierarchy: &Hierarchy, node: NodeId) -> Option<NodeId> {
|
||||||
|
hierarchy.nodes[&node].parent
|
||||||
|
}
|
||||||
|
|
||||||
|
fn inst(hierarchy: &Hierarchy, world: &WorldState, subject: SubjectId) -> NodeId {
|
||||||
|
let id = NodeId::of(world.world_id, &NodeAnchor::Institution(subject));
|
||||||
|
assert!(hierarchy.nodes.contains_key(&id), "no institution node");
|
||||||
|
id
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hierarchy_is_deterministic_and_ids_survive_an_unrelated_commit() {
|
||||||
|
let mut f = Fixture::new();
|
||||||
|
let town = f.place("Town", None);
|
||||||
|
let council = f.subject("Council", SubjectKind::Institution, None);
|
||||||
|
let alice = f.subject("Alice", SubjectKind::Person, Some(town));
|
||||||
|
f.grant(council, AuthorityTarget::PlaceSubtree(town));
|
||||||
|
f.office(council, "mayor", alice);
|
||||||
|
let first = derive_hierarchy(&f.state);
|
||||||
|
assert_eq!(first, derive_hierarchy(&f.state));
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::to_vec(&first).unwrap(),
|
||||||
|
serde_json::to_vec(&derive_hierarchy(&f.state)).unwrap()
|
||||||
|
);
|
||||||
|
// Time passes and an unrelated subject acts: no node changes identity.
|
||||||
|
f.state.now = FictionalMinutes(500);
|
||||||
|
f.state.revision += 7;
|
||||||
|
f.state.last_opportunity_at.insert(alice, FictionalMinutes(40));
|
||||||
|
let later = derive_hierarchy(&f.state);
|
||||||
|
assert_eq!(
|
||||||
|
first.nodes.keys().collect::<Vec<_>>(),
|
||||||
|
later.nodes.keys().collect::<Vec<_>>()
|
||||||
|
);
|
||||||
|
assert_eq!(first.home, later.home);
|
||||||
|
assert_eq!(later.last_attended.get(&alice), Some(&FictionalMinutes(40)));
|
||||||
|
assert!(first.last_attended.is_empty());
|
||||||
|
// The same anchor in another world is another node.
|
||||||
|
let other = NodeId::of(WorldId(Uuid::from_u128(0xbeef)), &NodeAnchor::World);
|
||||||
|
assert_ne!(other, first.root());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_voice_has_exactly_one_home_and_a_chain_to_the_root() {
|
||||||
|
let mut f = Fixture::new();
|
||||||
|
let region = f.place("Region", None);
|
||||||
|
let town = f.place("Town", Some(region));
|
||||||
|
let tavern = f.place("Tavern", Some(town));
|
||||||
|
let empire = f.subject("Empire", SubjectKind::Institution, None);
|
||||||
|
let council = f.subject("Council", SubjectKind::Institution, Some(town));
|
||||||
|
let guild = f.subject("Guild", SubjectKind::Institution, Some(tavern));
|
||||||
|
let folk = f.subject("Townsfolk", SubjectKind::Population, Some(town));
|
||||||
|
let alice = f.subject("Alice", SubjectKind::Person, Some(tavern));
|
||||||
|
let bob = f.subject("Bob", SubjectKind::Person, Some(region));
|
||||||
|
let nowhere = f.subject("Drifter", SubjectKind::Person, None);
|
||||||
|
let player = f.player(tavern);
|
||||||
|
f.grant(empire, AuthorityTarget::Subject(council));
|
||||||
|
f.grant(council, AuthorityTarget::PlaceSubtree(town));
|
||||||
|
f.office(guild, "master", alice);
|
||||||
|
let hierarchy = derive_hierarchy(&f.state);
|
||||||
|
|
||||||
|
let voices = [empire, council, guild, folk, alice, bob, nowhere];
|
||||||
|
for voice in voices {
|
||||||
|
let mut at = hierarchy.home[&voice];
|
||||||
|
let mut seen = BTreeSet::new();
|
||||||
|
loop {
|
||||||
|
assert!(seen.insert(at), "a chain revisited a node");
|
||||||
|
match parent_of(&hierarchy, at) {
|
||||||
|
Some(up) => at = up,
|
||||||
|
None => break,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert_eq!(at, hierarchy.root(), "a chain ended off the root");
|
||||||
|
// Exactly one place holds it: as a child node or as a loose subject.
|
||||||
|
let holders = hierarchy
|
||||||
|
.nodes
|
||||||
|
.values()
|
||||||
|
.filter(|node| node.loose.contains(&voice) || {
|
||||||
|
node.anchor == NodeAnchor::Institution(voice)
|
||||||
|
})
|
||||||
|
.count();
|
||||||
|
assert_eq!(holders, 1, "a voice is held by {holders} nodes");
|
||||||
|
}
|
||||||
|
assert_eq!(hierarchy.home.len(), voices.len() + 1, "the player is placed too");
|
||||||
|
assert!(hierarchy.home.contains_key(&player));
|
||||||
|
// A population is a single loose voice, hung by the same rule.
|
||||||
|
assert_eq!(hierarchy.home[&folk], inst(&hierarchy, &f.state, council));
|
||||||
|
assert_eq!(hierarchy.home[&nowhere], hierarchy.root());
|
||||||
|
// Children and parents agree.
|
||||||
|
for node in hierarchy.nodes.values() {
|
||||||
|
for child in &node.children {
|
||||||
|
assert_eq!(hierarchy.nodes[child].parent, Some(node.id));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn institutions_come_before_places() {
|
||||||
|
let mut f = Fixture::new();
|
||||||
|
let town = f.place("Town", None);
|
||||||
|
let tap_room = f.place("Tap-room", Some(town));
|
||||||
|
let field = f.place("Field", None);
|
||||||
|
let council = f.subject("Council", SubjectKind::Institution, None);
|
||||||
|
let guild = f.subject("Guild", SubjectKind::Institution, None);
|
||||||
|
let in_guild = f.subject("Guildsman", SubjectKind::Person, Some(tap_room));
|
||||||
|
let plain = f.subject("Drinker", SubjectKind::Person, Some(tap_room));
|
||||||
|
let farmer = f.subject("Farmer", SubjectKind::Person, Some(field));
|
||||||
|
f.grant(council, AuthorityTarget::PlaceSubtree(town));
|
||||||
|
f.office(guild, "member", in_guild);
|
||||||
|
let hierarchy = derive_hierarchy(&f.state);
|
||||||
|
assert_eq!(hierarchy.home[&in_guild], inst(&hierarchy, &f.state, guild));
|
||||||
|
assert_eq!(hierarchy.home[&plain], inst(&hierarchy, &f.state, council));
|
||||||
|
let field_node = NodeId::of(f.state.world_id, &NodeAnchor::Place(field));
|
||||||
|
assert_eq!(hierarchy.home[&farmer], field_node);
|
||||||
|
assert_eq!(parent_of(&hierarchy, field_node), Some(hierarchy.root()));
|
||||||
|
// A place node exists only where somebody hangs from it.
|
||||||
|
assert_eq!(
|
||||||
|
hierarchy
|
||||||
|
.nodes
|
||||||
|
.values()
|
||||||
|
.filter(|node| matches!(node.anchor, NodeAnchor::Place(_)))
|
||||||
|
.count(),
|
||||||
|
1
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_authority_grant_over_the_subject_beats_a_place_grant() {
|
||||||
|
let mut f = Fixture::new();
|
||||||
|
let town = f.place("Town", None);
|
||||||
|
let council = f.subject("Council", SubjectKind::Institution, None);
|
||||||
|
let temple = f.subject("Temple", SubjectKind::Institution, None);
|
||||||
|
let priest = f.subject("Priest", SubjectKind::Person, Some(town));
|
||||||
|
f.grant(council, AuthorityTarget::PlaceSubtree(town));
|
||||||
|
f.grant(temple, AuthorityTarget::Subject(priest));
|
||||||
|
let hierarchy = derive_hierarchy(&f.state);
|
||||||
|
assert_eq!(hierarchy.home[&priest], inst(&hierarchy, &f.state, temple));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_innermost_place_grant_governs_and_several_offices_pick_the_smaller_body() {
|
||||||
|
let mut f = Fixture::new();
|
||||||
|
let region = f.place("Region", None);
|
||||||
|
let town = f.place("Town", Some(region));
|
||||||
|
let crown = f.subject("Crown", SubjectKind::Institution, None);
|
||||||
|
let council = f.subject("Council", SubjectKind::Institution, None);
|
||||||
|
let big = f.subject("Big", SubjectKind::Institution, None);
|
||||||
|
let small = f.subject("Small", SubjectKind::Institution, None);
|
||||||
|
let walker = f.subject("Walker", SubjectKind::Person, Some(town));
|
||||||
|
let other_a = f.subject("A", SubjectKind::Person, None);
|
||||||
|
let other_b = f.subject("B", SubjectKind::Person, None);
|
||||||
|
let sitter = f.subject("Sitter", SubjectKind::Person, Some(town));
|
||||||
|
f.grant(crown, AuthorityTarget::PlaceSubtree(region));
|
||||||
|
f.grant(council, AuthorityTarget::PlaceSubtree(town));
|
||||||
|
f.office(big, "a", other_a);
|
||||||
|
f.office(big, "b", other_b);
|
||||||
|
f.office(big, "c", sitter);
|
||||||
|
f.office(small, "a", sitter);
|
||||||
|
let hierarchy = derive_hierarchy(&f.state);
|
||||||
|
assert_eq!(hierarchy.home[&walker], inst(&hierarchy, &f.state, council));
|
||||||
|
assert_eq!(hierarchy.home[&sitter], inst(&hierarchy, &f.state, small));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_cycle_is_broken_at_its_lowest_id() {
|
||||||
|
let mut f = Fixture::new();
|
||||||
|
let one = f.subject("One", SubjectKind::Institution, None);
|
||||||
|
let two = f.subject("Two", SubjectKind::Institution, None);
|
||||||
|
f.grant(one, AuthorityTarget::Subject(two));
|
||||||
|
f.grant(two, AuthorityTarget::Subject(one));
|
||||||
|
let (low, high) = if one < two { (one, two) } else { (two, one) };
|
||||||
|
let hierarchy = derive_hierarchy(&f.state);
|
||||||
|
assert_eq!(hierarchy.home[&low], hierarchy.root());
|
||||||
|
assert_eq!(hierarchy.home[&high], inst(&hierarchy, &f.state, low));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_tail_leading_into_a_cycle_keeps_its_parent_when_the_cycle_breaks() {
|
||||||
|
let mut f = Fixture::new();
|
||||||
|
let tail = f.subject("Tail", SubjectKind::Institution, None);
|
||||||
|
let one = f.subject("One", SubjectKind::Institution, None);
|
||||||
|
let two = f.subject("Two", SubjectKind::Institution, None);
|
||||||
|
f.grant(one, AuthorityTarget::Subject(tail));
|
||||||
|
f.grant(one, AuthorityTarget::Subject(two));
|
||||||
|
f.grant(two, AuthorityTarget::Subject(one));
|
||||||
|
let hierarchy = derive_hierarchy(&f.state);
|
||||||
|
assert_eq!(hierarchy.home[&tail], inst(&hierarchy, &f.state, one));
|
||||||
|
assert_eq!(hierarchy.home[&one], hierarchy.root());
|
||||||
|
assert_eq!(hierarchy.home[&two], inst(&hierarchy, &f.state, one));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_player_is_placed_and_never_a_voice() {
|
||||||
|
let mut f = Fixture::new();
|
||||||
|
let town = f.place("Town", None);
|
||||||
|
let council = f.subject("Council", SubjectKind::Institution, None);
|
||||||
|
let player = f.player(town);
|
||||||
|
f.grant(council, AuthorityTarget::PlaceSubtree(town));
|
||||||
|
f.office(council, "seat", player);
|
||||||
|
let hierarchy = derive_hierarchy(&f.state);
|
||||||
|
assert_eq!(hierarchy.home[&player], inst(&hierarchy, &f.state, council));
|
||||||
|
assert!(
|
||||||
|
hierarchy
|
||||||
|
.nodes
|
||||||
|
.values()
|
||||||
|
.all(|node| node.voice != Some(player) && !node.loose.contains(&player))
|
||||||
|
);
|
||||||
|
assert!(!hierarchy.last_attended.contains_key(&player));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_focus_path_follows_governance() {
|
||||||
|
let mut f = Fixture::new();
|
||||||
|
let town = f.place("Town", None);
|
||||||
|
let tap_room = f.place("Tap-room", Some(town));
|
||||||
|
let heath = f.place("Heath", None);
|
||||||
|
let empire = f.subject("Empire", SubjectKind::Institution, None);
|
||||||
|
let council = f.subject("Council", SubjectKind::Institution, None);
|
||||||
|
f.subject("Drinker", SubjectKind::Person, Some(tap_room));
|
||||||
|
f.grant(council, AuthorityTarget::PlaceSubtree(town));
|
||||||
|
f.grant(empire, AuthorityTarget::Subject(council));
|
||||||
|
let hierarchy = derive_hierarchy(&f.state);
|
||||||
|
assert_eq!(
|
||||||
|
hierarchy.focus_path(tap_room),
|
||||||
|
vec![
|
||||||
|
inst(&hierarchy, &f.state, council),
|
||||||
|
inst(&hierarchy, &f.state, empire),
|
||||||
|
hierarchy.root(),
|
||||||
|
]
|
||||||
|
);
|
||||||
|
// An ungoverned place is governed by the root alone.
|
||||||
|
assert_eq!(hierarchy.focus_path(heath), vec![hierarchy.root()]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_place_node_hangs_from_the_nearest_enclosing_place_node() {
|
||||||
|
let mut f = Fixture::new();
|
||||||
|
let region = f.place("Region", None);
|
||||||
|
let hamlet = f.place("Hamlet", Some(region));
|
||||||
|
let barn = f.place("Barn", Some(hamlet));
|
||||||
|
f.subject("Reeve", SubjectKind::Person, Some(region));
|
||||||
|
f.subject("Hand", SubjectKind::Person, Some(barn));
|
||||||
|
let hierarchy = derive_hierarchy(&f.state);
|
||||||
|
let region_node = NodeId::of(f.state.world_id, &NodeAnchor::Place(region));
|
||||||
|
let barn_node = NodeId::of(f.state.world_id, &NodeAnchor::Place(barn));
|
||||||
|
assert_eq!(parent_of(&hierarchy, barn_node), Some(region_node));
|
||||||
|
assert_eq!(
|
||||||
|
hierarchy.focus_path(hamlet),
|
||||||
|
vec![region_node, hierarchy.root()]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
752
crates/ghostlight/src/import_key_tests.rs
Normal file
752
crates/ghostlight/src/import_key_tests.rs
Normal file
|
|
@ -0,0 +1,752 @@
|
||||||
|
//! One record, one subject: admission keeps the import-key mapping injective at
|
||||||
|
//! every door and at every revision, and a world nobody imported into is
|
||||||
|
//! byte-for-byte what it was before keys existed.
|
||||||
|
|
||||||
|
use crate::patch::{
|
||||||
|
AccessKind, ComponentOp, Cost, Declaration, DraftHandle, EntityDeclaration, EntityKind,
|
||||||
|
ImportKey, Mismatch, Ref, RouteDeclaration,
|
||||||
|
};
|
||||||
|
use crate::tests::{activate, auth_principal, command, creation, owner};
|
||||||
|
use crate::{
|
||||||
|
CallerId, CommandBody, CommandId, ConsumerId, CreateWorld, EntityId, JurisdictionKey,
|
||||||
|
KernelError, NewController, PatchAnswer, SubjectDeclaration, SubjectKind, SubmitReceipt,
|
||||||
|
SystemCapability, WorldKernel, WorldPatch,
|
||||||
|
};
|
||||||
|
use std::collections::BTreeSet;
|
||||||
|
|
||||||
|
fn key(schema: &str, record: &str) -> ImportKey {
|
||||||
|
ImportKey::new(schema, record)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn alpha() -> ImportKey {
|
||||||
|
key("aetheria.ship", "Alpha")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The fixture genesis with its witness imported from `alpha()`.
|
||||||
|
fn keyed_creation(title: &str) -> CreateWorld {
|
||||||
|
let mut world = creation(CommandId::new(), title);
|
||||||
|
for declaration in &mut world.patch.declarations {
|
||||||
|
if let Declaration::Subject(subject) = declaration
|
||||||
|
&& subject.handle == DraftHandle::new("persona")
|
||||||
|
{
|
||||||
|
subject.import_key = Some(alpha());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
world
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create(world: CreateWorld) -> (tempfile::TempDir, Result<WorldKernel, KernelError>) {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let result = WorldKernel::create(
|
||||||
|
directory.path().join("world.cc"),
|
||||||
|
world,
|
||||||
|
&auth_principal(owner()),
|
||||||
|
)
|
||||||
|
.map(|(kernel, _)| kernel);
|
||||||
|
(directory, result)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn keyed_world() -> (tempfile::TempDir, WorldKernel) {
|
||||||
|
let (dir, kernel) = create(keyed_creation("Keyed"));
|
||||||
|
(dir, kernel.unwrap())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rejected(result: Result<impl Sized, KernelError>) -> Vec<Mismatch> {
|
||||||
|
match result {
|
||||||
|
Err(KernelError::PatchRejected(set)) => set,
|
||||||
|
Err(other) => panic!("expected a patch refusal, got {other:?}"),
|
||||||
|
Ok(_) => panic!("expected a patch refusal, the command was admitted"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn patch_of(declarations: Vec<Declaration>) -> WorldPatch {
|
||||||
|
WorldPatch {
|
||||||
|
declarations,
|
||||||
|
operations: Vec::new(),
|
||||||
|
evidence: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn submit_as(
|
||||||
|
kernel: &mut WorldKernel,
|
||||||
|
caller: CallerId,
|
||||||
|
answers: Option<PatchAnswer>,
|
||||||
|
patch: WorldPatch,
|
||||||
|
) -> Result<SubmitReceipt, KernelError> {
|
||||||
|
let snapshot = kernel.snapshot().unwrap();
|
||||||
|
kernel.submit(
|
||||||
|
command(
|
||||||
|
&snapshot,
|
||||||
|
CommandId::new(),
|
||||||
|
caller.clone(),
|
||||||
|
CommandBody::AdmitPatch { answers, patch },
|
||||||
|
),
|
||||||
|
&crate::AuthenticatedCaller::fixture(caller),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn commons(kernel: &WorldKernel) -> EntityId {
|
||||||
|
*kernel.state.entities.keys().next().unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A mirror subject: the one shape every door may declare, since it needs no
|
||||||
|
/// catalog grant.
|
||||||
|
fn mirror(handle: &str, import_key: Option<ImportKey>, place: EntityId) -> Declaration {
|
||||||
|
Declaration::Subject(SubjectDeclaration {
|
||||||
|
handle: DraftHandle::new(handle),
|
||||||
|
label: format!("The {handle}"),
|
||||||
|
kind: SubjectKind::Person,
|
||||||
|
controller: NewController::External {
|
||||||
|
consumer: ConsumerId::of_name("import-key"),
|
||||||
|
},
|
||||||
|
affordances: BTreeSet::new(),
|
||||||
|
position: Some(Ref::Existing(place)),
|
||||||
|
import_key,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn held(handle: &str) -> Mismatch {
|
||||||
|
Mismatch::ImportKeyHeld {
|
||||||
|
handle: DraftHandle::new(handle),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn duplicate(handle: &str) -> Mismatch {
|
||||||
|
Mismatch::DuplicateImportKey {
|
||||||
|
handle: DraftHandle::new(handle),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn malformed(handle: &str) -> Mismatch {
|
||||||
|
Mismatch::MalformedImportKey {
|
||||||
|
handle: DraftHandle::new(handle),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn keys_in(kernel: &WorldKernel) -> Vec<ImportKey> {
|
||||||
|
kernel
|
||||||
|
.snapshot()
|
||||||
|
.unwrap()
|
||||||
|
.subjects
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|subject| subject.import_key)
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn one_patch_cannot_declare_two_subjects_with_one_import_key() {
|
||||||
|
// At genesis.
|
||||||
|
let mut world = creation(CommandId::new(), "Twins");
|
||||||
|
for declaration in &mut world.patch.declarations {
|
||||||
|
if let Declaration::Subject(subject) = declaration
|
||||||
|
&& (subject.handle == DraftHandle::new("persona")
|
||||||
|
|| subject.handle == DraftHandle::new("operator"))
|
||||||
|
{
|
||||||
|
subject.import_key = Some(alpha());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let (_dir, result) = create(world);
|
||||||
|
assert_eq!(rejected(result), vec![duplicate("operator")]);
|
||||||
|
|
||||||
|
// In a later patch, with the key unheld.
|
||||||
|
let (_dir, mut kernel) = keyed_world();
|
||||||
|
let place = commons(&kernel);
|
||||||
|
let revision = kernel.state.revision;
|
||||||
|
let beta = Some(key("aetheria.ship", "Beta"));
|
||||||
|
let error = submit_as(
|
||||||
|
&mut kernel,
|
||||||
|
CallerId::Principal(owner()),
|
||||||
|
None,
|
||||||
|
patch_of(vec![
|
||||||
|
mirror("first", beta.clone(), place),
|
||||||
|
mirror("second", beta, place),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
assert_eq!(rejected(error), vec![duplicate("second")]);
|
||||||
|
assert_eq!(kernel.state.revision, revision, "a refusal moved the world");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The fixture world past genesis but still in Draft: the owner has added an
|
||||||
|
/// unwalked place the elaborator can later answer.
|
||||||
|
fn advanced_keyed_world() -> (tempfile::TempDir, WorldKernel, EntityId) {
|
||||||
|
let (dir, mut kernel) = keyed_world();
|
||||||
|
let place = commons(&kernel);
|
||||||
|
submit_as(
|
||||||
|
&mut kernel,
|
||||||
|
CallerId::Principal(owner()),
|
||||||
|
None,
|
||||||
|
patch_of(vec![
|
||||||
|
Declaration::Entity(EntityDeclaration {
|
||||||
|
handle: DraftHandle::new("dead-end"),
|
||||||
|
label: "The Unwalked Road".into(),
|
||||||
|
kind: EntityKind::Place,
|
||||||
|
container: None,
|
||||||
|
}),
|
||||||
|
Declaration::Route(RouteDeclaration {
|
||||||
|
handle: DraftHandle::new("gate"),
|
||||||
|
label: "The Field Gate".into(),
|
||||||
|
from: Ref::Existing(place),
|
||||||
|
to: Ref::Draft(DraftHandle::new("dead-end")),
|
||||||
|
access: AccessKind::Public,
|
||||||
|
cost: Cost(1),
|
||||||
|
}),
|
||||||
|
]),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let dead_end = *kernel
|
||||||
|
.state
|
||||||
|
.entities
|
||||||
|
.iter()
|
||||||
|
.find(|(_, record)| record.label == "The Unwalked Road")
|
||||||
|
.map(|(id, _)| id)
|
||||||
|
.unwrap();
|
||||||
|
(dir, kernel, dead_end)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Each door names the held key, typed, and the refusal leaves the revision
|
||||||
|
/// where it was. The owner and the consumer declare in Draft only; Play and the
|
||||||
|
/// elaborator act in Active.
|
||||||
|
fn refuse_held_key_at_each_door(
|
||||||
|
kernel: &mut WorldKernel,
|
||||||
|
place: EntityId,
|
||||||
|
doors: Vec<(&str, CallerId, Option<PatchAnswer>)>,
|
||||||
|
) {
|
||||||
|
for (door, caller, answers) in doors {
|
||||||
|
let revision = kernel.state.revision;
|
||||||
|
let result = submit_as(
|
||||||
|
kernel,
|
||||||
|
caller,
|
||||||
|
answers,
|
||||||
|
patch_of(vec![mirror("copy", Some(alpha()), place)]),
|
||||||
|
);
|
||||||
|
assert_eq!(rejected(result), vec![held("copy")], "{door}");
|
||||||
|
assert_eq!(
|
||||||
|
kernel.state.revision, revision,
|
||||||
|
"{door} refusal moved the world"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn consumer() -> CallerId {
|
||||||
|
CallerId::System(SystemCapability::Consumer {
|
||||||
|
consumer: ConsumerId::of_name("import-key"),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_held_import_key_is_refused_at_every_door_after_the_revision_has_moved() {
|
||||||
|
let (_dir, mut kernel, dead_end) = advanced_keyed_world();
|
||||||
|
assert!(kernel.state.revision > 0, "the world has moved past genesis");
|
||||||
|
refuse_held_key_at_each_door(
|
||||||
|
&mut kernel,
|
||||||
|
dead_end,
|
||||||
|
vec![
|
||||||
|
("owner", CallerId::Principal(owner()), None),
|
||||||
|
("consumer", consumer(), None),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
activate(&mut kernel);
|
||||||
|
let answer = crate::derive_boundaries(&kernel.state)
|
||||||
|
.unwrap()
|
||||||
|
.into_iter()
|
||||||
|
.find(|boundary| {
|
||||||
|
matches!(boundary, crate::CausalBoundary::UnelaboratedDestination { place, .. }
|
||||||
|
if *place == dead_end)
|
||||||
|
})
|
||||||
|
.expect("the dead end is an unelaborated destination");
|
||||||
|
refuse_held_key_at_each_door(
|
||||||
|
&mut kernel,
|
||||||
|
dead_end,
|
||||||
|
vec![
|
||||||
|
("play", CallerId::System(SystemCapability::Play), None),
|
||||||
|
(
|
||||||
|
"elaborator",
|
||||||
|
CallerId::System(SystemCapability::Elaborator {
|
||||||
|
jurisdiction: JurisdictionKey::PlaceSubtree(dead_end),
|
||||||
|
}),
|
||||||
|
Some(PatchAnswer::Boundary(answer.clone())),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
// The same doors admit an unheld key, so the refusals are the key's; and
|
||||||
|
// what a door admitted is held against every later door.
|
||||||
|
let fresh = key("aetheria.ship", "Gamma");
|
||||||
|
let receipt = submit_as(
|
||||||
|
&mut kernel,
|
||||||
|
CallerId::System(SystemCapability::Elaborator {
|
||||||
|
jurisdiction: JurisdictionKey::PlaceSubtree(dead_end),
|
||||||
|
}),
|
||||||
|
Some(PatchAnswer::Boundary(answer)),
|
||||||
|
patch_of(vec![mirror("fresh", Some(fresh.clone()), dead_end)]),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert!(matches!(receipt, SubmitReceipt::Applied(_)));
|
||||||
|
let again = submit_as(
|
||||||
|
&mut kernel,
|
||||||
|
CallerId::System(SystemCapability::Play),
|
||||||
|
None,
|
||||||
|
patch_of(vec![mirror("fresh-again", Some(fresh), dead_end)]),
|
||||||
|
);
|
||||||
|
assert_eq!(rejected(again), vec![held("fresh-again")]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_held_import_key_is_refused_in_a_later_patch() {
|
||||||
|
let (_dir, mut kernel) = keyed_world();
|
||||||
|
let place = commons(&kernel);
|
||||||
|
let revision = kernel.state.revision;
|
||||||
|
let error = submit_as(
|
||||||
|
&mut kernel,
|
||||||
|
CallerId::Principal(owner()),
|
||||||
|
None,
|
||||||
|
patch_of(vec![mirror("again", Some(alpha()), place)]),
|
||||||
|
);
|
||||||
|
assert_eq!(rejected(error), vec![held("again")]);
|
||||||
|
assert_eq!(kernel.state.revision, revision);
|
||||||
|
assert_eq!(keys_in(&kernel), vec![alpha()]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_retired_subjects_import_key_is_never_reissued() {
|
||||||
|
let (_dir, mut kernel) = keyed_world();
|
||||||
|
let place = commons(&kernel);
|
||||||
|
let witness = kernel
|
||||||
|
.snapshot()
|
||||||
|
.unwrap()
|
||||||
|
.subjects
|
||||||
|
.into_iter()
|
||||||
|
.find(|subject| subject.import_key.is_some())
|
||||||
|
.unwrap()
|
||||||
|
.id;
|
||||||
|
submit_as(
|
||||||
|
&mut kernel,
|
||||||
|
CallerId::Principal(owner()),
|
||||||
|
None,
|
||||||
|
WorldPatch {
|
||||||
|
declarations: Vec::new(),
|
||||||
|
operations: vec![ComponentOp::Retire {
|
||||||
|
subject: Ref::Existing(witness),
|
||||||
|
}],
|
||||||
|
evidence: Vec::new(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let retired = kernel
|
||||||
|
.snapshot()
|
||||||
|
.unwrap()
|
||||||
|
.subjects
|
||||||
|
.into_iter()
|
||||||
|
.find(|subject| subject.id == witness)
|
||||||
|
.unwrap();
|
||||||
|
assert!(retired.retired, "the witness is retired");
|
||||||
|
assert_eq!(
|
||||||
|
retired.import_key,
|
||||||
|
Some(alpha()),
|
||||||
|
"a retired subject keeps its key"
|
||||||
|
);
|
||||||
|
let error = submit_as(
|
||||||
|
&mut kernel,
|
||||||
|
CallerId::Principal(owner()),
|
||||||
|
None,
|
||||||
|
patch_of(vec![mirror("reborn", Some(alpha()), place)]),
|
||||||
|
);
|
||||||
|
assert_eq!(rejected(error), vec![held("reborn")]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn keys_that_differ_in_any_way_are_distinct_records() {
|
||||||
|
let (_dir, mut kernel) = keyed_world();
|
||||||
|
let place = commons(&kernel);
|
||||||
|
// Same length, case, prefix, the same concatenation split elsewhere, and
|
||||||
|
// the parts swapped: none is the held key.
|
||||||
|
let forgeries = [
|
||||||
|
key("aetheria.ship", "Alphb"),
|
||||||
|
key("aetheria.ship", "alpha"),
|
||||||
|
key("aetheria.ship", "Alph"),
|
||||||
|
key("aetheria.ship", "Alpha2"),
|
||||||
|
key("aetheria.shipA", "lpha"),
|
||||||
|
key("aetheria.sh", "ipAlpha"),
|
||||||
|
key("Aetheria.ship", "Alpha"),
|
||||||
|
key("Alpha", "aetheria.ship"),
|
||||||
|
key("aetheria.ship2", "Alpha"),
|
||||||
|
];
|
||||||
|
let declarations = forgeries
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(index, forged)| mirror(&format!("forged-{index}"), Some(forged.clone()), place))
|
||||||
|
.collect();
|
||||||
|
submit_as(
|
||||||
|
&mut kernel,
|
||||||
|
CallerId::Principal(owner()),
|
||||||
|
None,
|
||||||
|
patch_of(declarations),
|
||||||
|
)
|
||||||
|
.expect("nine distinct keys beside the held one are admitted together");
|
||||||
|
let held_now: BTreeSet<ImportKey> = keys_in(&kernel).into_iter().collect();
|
||||||
|
assert_eq!(held_now.len(), forgeries.len() + 1);
|
||||||
|
// And each is then held exactly: repeating any one is refused.
|
||||||
|
for (index, forged) in forgeries.iter().enumerate() {
|
||||||
|
let again = submit_as(
|
||||||
|
&mut kernel,
|
||||||
|
CallerId::Principal(owner()),
|
||||||
|
None,
|
||||||
|
patch_of(vec![mirror("repeat", Some(forged.clone()), place)]),
|
||||||
|
);
|
||||||
|
assert_eq!(rejected(again), vec![held("repeat")], "forgery {index}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_malformed_import_key_is_refused_without_echoing_it() {
|
||||||
|
let (_dir, mut kernel) = keyed_world();
|
||||||
|
let place = commons(&kernel);
|
||||||
|
let long = "x".repeat(201);
|
||||||
|
let wide = "é".repeat(101);
|
||||||
|
let cases = [
|
||||||
|
key("", "Delta"),
|
||||||
|
key("aetheria.ship", ""),
|
||||||
|
key("aetheria ship", "Delta"),
|
||||||
|
key("aetheria.ship", "Del\tta"),
|
||||||
|
key("aetheria.ship", "Del\u{a0}ta"),
|
||||||
|
key("aetheria.ship", " Delta"),
|
||||||
|
key("aetheria.ship", "Delta\n"),
|
||||||
|
key(&long, "Delta"),
|
||||||
|
key("aetheria.ship", &long),
|
||||||
|
key("aetheria.ship", &wide),
|
||||||
|
key(&wide, "Delta"),
|
||||||
|
];
|
||||||
|
for (index, bad) in cases.iter().enumerate() {
|
||||||
|
let set = rejected(submit_as(
|
||||||
|
&mut kernel,
|
||||||
|
CallerId::Principal(owner()),
|
||||||
|
None,
|
||||||
|
patch_of(vec![mirror("bad", Some(bad.clone()), place)]),
|
||||||
|
));
|
||||||
|
assert_eq!(set, vec![malformed("bad")], "case {index}");
|
||||||
|
let spelled = format!("{set:?}");
|
||||||
|
assert!(
|
||||||
|
!spelled.contains("Delta") && !spelled.contains("aetheria"),
|
||||||
|
"case {index} echoed the key"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// The limit is 200 bytes per part, counted in bytes.
|
||||||
|
let edge = "é".repeat(100);
|
||||||
|
let at_limit = [
|
||||||
|
key(&"x".repeat(200), &edge),
|
||||||
|
key("aetheria.ship", &"y".repeat(200)),
|
||||||
|
];
|
||||||
|
let declarations = at_limit
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(index, limit)| mirror(&format!("edge-{index}"), Some(limit.clone()), place))
|
||||||
|
.collect();
|
||||||
|
submit_as(
|
||||||
|
&mut kernel,
|
||||||
|
CallerId::Principal(owner()),
|
||||||
|
None,
|
||||||
|
patch_of(declarations),
|
||||||
|
)
|
||||||
|
.expect("keys of exactly 200 bytes per part are admitted");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_subjects_map_refuses_a_second_subject_for_one_key_even_when_resolved_elsewhere() {
|
||||||
|
let (_dir, kernel) = keyed_world();
|
||||||
|
let place = commons(&kernel);
|
||||||
|
let resolve = |handle: &str| {
|
||||||
|
crate::patch::resolve_patch(
|
||||||
|
&kernel.state,
|
||||||
|
CommandId::new(),
|
||||||
|
&patch_of(vec![mirror(
|
||||||
|
handle,
|
||||||
|
Some(key("aetheria.ship", "Omega")),
|
||||||
|
place,
|
||||||
|
)]),
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.expect("the key is unheld at the revision both were resolved against")
|
||||||
|
};
|
||||||
|
let (first, second) = (resolve("first"), resolve("second"));
|
||||||
|
let mut state = kernel.state.clone();
|
||||||
|
let before = state.subjects.len();
|
||||||
|
let effect = |resolved| crate::WorldEffect::PatchAdmitted {
|
||||||
|
answers: None,
|
||||||
|
resolved,
|
||||||
|
};
|
||||||
|
crate::apply_effect(
|
||||||
|
&mut state,
|
||||||
|
CommandId::new(),
|
||||||
|
&CallerId::Principal(owner()),
|
||||||
|
&effect(first),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(state.subjects.len(), before + 1);
|
||||||
|
let result = crate::apply_effect(
|
||||||
|
&mut state,
|
||||||
|
CommandId::new(),
|
||||||
|
&CallerId::Principal(owner()),
|
||||||
|
&effect(second),
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
matches!(result, Err(KernelError::Invariant(_))),
|
||||||
|
"{result:?}"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
state.subjects.len(),
|
||||||
|
before + 1,
|
||||||
|
"the second subject was installed"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn contains(haystack: &[u8], needle: &[u8]) -> bool {
|
||||||
|
haystack.windows(needle.len()).any(|window| window == needle)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn keyless_world_digests_unchanged() {
|
||||||
|
// A subject nobody imported serialises without the field at all, so every
|
||||||
|
// digest written before keys existed is the digest of the same bytes.
|
||||||
|
let (_dir, kernel) = create(creation(CommandId::new(), "Keyless"));
|
||||||
|
let kernel = kernel.unwrap();
|
||||||
|
let state = rmp_serde::to_vec_named(&kernel.state).unwrap();
|
||||||
|
assert!(
|
||||||
|
!contains(&state, b"import_key"),
|
||||||
|
"a keyless world grew a field"
|
||||||
|
);
|
||||||
|
// A keyed world carries it, round-trips, and digests differently.
|
||||||
|
let (_dir, keyed) = keyed_world();
|
||||||
|
let keyed_state = rmp_serde::to_vec_named(&keyed.state).unwrap();
|
||||||
|
assert!(contains(&keyed_state, b"import_key"));
|
||||||
|
let back: crate::WorldState = rmp_serde::from_slice(&keyed_state).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
crate::state_digest(&back).unwrap(),
|
||||||
|
crate::state_digest(&keyed.state).unwrap()
|
||||||
|
);
|
||||||
|
assert_ne!(
|
||||||
|
crate::state_digest(&keyed.state).unwrap(),
|
||||||
|
crate::state_digest(&kernel.state).unwrap()
|
||||||
|
);
|
||||||
|
// And a pre-key state deserialises with every key absent.
|
||||||
|
let stripped: crate::WorldState = rmp_serde::from_slice(&state).unwrap();
|
||||||
|
assert!(stripped.subjects.values().all(|s| s.import_key.is_none()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_keyed_world_reopens_with_its_keys_and_digests() {
|
||||||
|
let (dir, kernel) = keyed_world();
|
||||||
|
let snapshot = kernel.snapshot().unwrap();
|
||||||
|
let world_id = snapshot.world_id;
|
||||||
|
drop(kernel);
|
||||||
|
let reopened = WorldKernel::open(dir.path().join("world.cc"), world_id).unwrap();
|
||||||
|
let again = reopened.snapshot().unwrap();
|
||||||
|
assert_eq!(again.state_digest, snapshot.state_digest);
|
||||||
|
let keys = keys_in(&reopened);
|
||||||
|
assert_eq!(keys, vec![alpha()]);
|
||||||
|
// A reader of the snapshot gets both parts back, separately.
|
||||||
|
assert_eq!(keys[0].schema(), "aetheria.ship");
|
||||||
|
assert_eq!(keys[0].record(), "Alpha");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_record_key_is_one_canonical_spelling() {
|
||||||
|
let (_dir, mut kernel) = keyed_world();
|
||||||
|
let place = commons(&kernel);
|
||||||
|
let nfc = "Caf\u{e9}";
|
||||||
|
let nfd = "Cafe\u{301}";
|
||||||
|
let submit = |kernel: &mut WorldKernel, handle: &str, record: &str| {
|
||||||
|
submit_as(
|
||||||
|
kernel,
|
||||||
|
CallerId::Principal(owner()),
|
||||||
|
None,
|
||||||
|
patch_of(vec![mirror(
|
||||||
|
handle,
|
||||||
|
Some(key("aetheria.ship", record)),
|
||||||
|
place,
|
||||||
|
)]),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
submit(&mut kernel, "nfc", nfc).expect("the NFC spelling is admitted");
|
||||||
|
let refused = [
|
||||||
|
nfd,
|
||||||
|
"Alpha\u{200b}",
|
||||||
|
"Alpha\u{0}",
|
||||||
|
"\u{feff}Alpha",
|
||||||
|
"Alpha\u{202e}",
|
||||||
|
"Alpha\u{7}",
|
||||||
|
"Del ta",
|
||||||
|
"Del\tta",
|
||||||
|
"Del\u{a0}ta",
|
||||||
|
"Del\u{2003}ta",
|
||||||
|
"Del\nta",
|
||||||
|
// The violation sits deep in a long, real-shaped path, past any prefix.
|
||||||
|
"Worldbuilding/Pre-Elysium/Factions/Powers/Minor/Cafe\u{301}",
|
||||||
|
"Worldbuilding/Pre-Elysium/Factions/Powers/Minor/Ewan\u{200b}Hart",
|
||||||
|
];
|
||||||
|
for (index, record) in refused.iter().enumerate() {
|
||||||
|
let set = rejected(submit(&mut kernel, "bad", record));
|
||||||
|
assert_eq!(set, vec![malformed("bad")], "spelling {index}");
|
||||||
|
assert!(
|
||||||
|
!format!("{set:?}").contains("Alpha"),
|
||||||
|
"spelling {index} echoed the key"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert_eq!(
|
||||||
|
keys_in(&kernel).len(),
|
||||||
|
2,
|
||||||
|
"only the genesis key and the NFC key are held"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_lore_page_path_with_spaces_is_a_record_key() {
|
||||||
|
let (_dir, mut kernel) = keyed_world();
|
||||||
|
let place = commons(&kernel);
|
||||||
|
let record = "Worldbuilding/Pre-Elysium/Factions/Powers/Minor/Ewan Hart";
|
||||||
|
let declare = |kernel: &mut WorldKernel, handle: &str| {
|
||||||
|
submit_as(
|
||||||
|
kernel,
|
||||||
|
CallerId::Principal(owner()),
|
||||||
|
None,
|
||||||
|
patch_of(vec![mirror(
|
||||||
|
handle,
|
||||||
|
Some(key("aetheria.lore", record)),
|
||||||
|
place,
|
||||||
|
)]),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
declare(&mut kernel, "ewan").expect("a path with interior spaces is admitted");
|
||||||
|
assert_eq!(rejected(declare(&mut kernel, "again")), vec![held("again")]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_loaded_state_with_a_bad_import_key_is_refused() {
|
||||||
|
let (_dir, mut kernel) = keyed_world();
|
||||||
|
let place = commons(&kernel);
|
||||||
|
submit_as(
|
||||||
|
&mut kernel,
|
||||||
|
CallerId::Principal(owner()),
|
||||||
|
None,
|
||||||
|
patch_of(vec![mirror(
|
||||||
|
"beta",
|
||||||
|
Some(key("aetheria.ship", "Beta")),
|
||||||
|
place,
|
||||||
|
)]),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert!(crate::journal::verify_state_shape(&kernel.state).is_ok());
|
||||||
|
let corrupt = |edit: &dyn Fn(&mut ImportKey)| {
|
||||||
|
let mut state = kernel.state.clone();
|
||||||
|
for subject in state.subjects.values_mut() {
|
||||||
|
if let Some(held) = subject.import_key.as_mut() {
|
||||||
|
edit(held);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
crate::journal::verify_state_shape(&state)
|
||||||
|
};
|
||||||
|
let shared = corrupt(&|held| *held = alpha());
|
||||||
|
assert!(
|
||||||
|
matches!(&shared, Err(crate::journal::JournalError::Corrupt(why)) if why.contains("import key")),
|
||||||
|
"two subjects sharing one key: {shared:?}"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
corrupt(&|held| *held = key("aetheria.ship", " Beta ")).is_err(),
|
||||||
|
"a key with edge spaces must not load"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
corrupt(&|held| *held = key("", "")).is_err(),
|
||||||
|
"an empty key must not load"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
corrupt(&|held| *held = key("aetheria.ship", "Be\u{200b}ta")).is_err(),
|
||||||
|
"a key with a format character must not load"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The admission backstop, reached with an effect resolution never produced: a
|
||||||
|
/// resolved patch whose two subjects carry one key. The control is the same
|
||||||
|
/// effect with distinct keys, admitted by the same function.
|
||||||
|
#[test]
|
||||||
|
fn admitting_a_resolved_effect_refuses_two_subjects_with_one_key() {
|
||||||
|
let (_dir, kernel) = keyed_world();
|
||||||
|
let place = commons(&kernel);
|
||||||
|
let resolve = || {
|
||||||
|
crate::patch::resolve_patch(
|
||||||
|
&kernel.state,
|
||||||
|
CommandId::new(),
|
||||||
|
&patch_of(vec![
|
||||||
|
mirror("first", Some(key("aetheria.ship", "Beta")), place),
|
||||||
|
mirror("second", Some(key("aetheria.ship", "Gamma")), place),
|
||||||
|
]),
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.expect("two distinct keys resolve")
|
||||||
|
};
|
||||||
|
let resolves_to = crate::resolution_revision(&kernel.state).unwrap();
|
||||||
|
let mut control = kernel.state.clone();
|
||||||
|
crate::admit_resolved(&mut control, &resolve(), resolves_to)
|
||||||
|
.expect("distinct keys are admitted");
|
||||||
|
|
||||||
|
let mut twinned = resolve();
|
||||||
|
assert_eq!(twinned.subjects.len(), 2);
|
||||||
|
twinned.subjects[1].subject.import_key = twinned.subjects[0].subject.import_key.clone();
|
||||||
|
let mut state = kernel.state.clone();
|
||||||
|
let error = crate::admit_resolved(&mut state, &twinned, resolves_to)
|
||||||
|
.expect_err("one key on two resolved subjects is refused");
|
||||||
|
assert!(
|
||||||
|
matches!(&error, KernelError::Invariant(why) if why.contains("import key")),
|
||||||
|
"{error:?}"
|
||||||
|
);
|
||||||
|
assert!(!format!("{error:?}").contains("Beta"), "the refusal echoed the key");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A decomposable character at every position of a real-shaped key: the NFD
|
||||||
|
/// spelling is refused wherever it sits, the NFC spelling is admitted, so the
|
||||||
|
/// rule cannot be a prefix, suffix or first-character check.
|
||||||
|
#[test]
|
||||||
|
fn a_decomposable_character_is_refused_in_nfd_at_every_position() {
|
||||||
|
let (_dir, mut kernel) = keyed_world();
|
||||||
|
let place = commons(&kernel);
|
||||||
|
let template: Vec<char> = "Worldbuilding/Pre-Elysium/Factions/Powers/Minor/Ewan Hart"
|
||||||
|
.chars()
|
||||||
|
.collect();
|
||||||
|
let submit = |kernel: &mut WorldKernel, handle: &str, record: String| {
|
||||||
|
submit_as(
|
||||||
|
kernel,
|
||||||
|
CallerId::Principal(owner()),
|
||||||
|
None,
|
||||||
|
patch_of(vec![mirror(
|
||||||
|
handle,
|
||||||
|
Some(key("aetheria.lore", &record)),
|
||||||
|
place,
|
||||||
|
)]),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
let spelled = |position: usize, inserted: &str| {
|
||||||
|
let mut record: String = template[..position].iter().collect();
|
||||||
|
record.push_str(inserted);
|
||||||
|
record.extend(&template[position..]);
|
||||||
|
record
|
||||||
|
};
|
||||||
|
for position in 0..=template.len() {
|
||||||
|
let nfd = spelled(position, "e\u{301}");
|
||||||
|
assert!(
|
||||||
|
!unicode_normalization::is_nfc(&nfd),
|
||||||
|
"position {position} is not NFD"
|
||||||
|
);
|
||||||
|
let set = rejected(submit(&mut kernel, "bad", nfd));
|
||||||
|
assert_eq!(set, vec![malformed("bad")], "NFD at position {position}");
|
||||||
|
}
|
||||||
|
for position in 0..=template.len() {
|
||||||
|
let nfc = spelled(position, "\u{e9}");
|
||||||
|
submit(&mut kernel, &format!("good{position}"), nfc)
|
||||||
|
.unwrap_or_else(|_| panic!("NFC at position {position} was refused"));
|
||||||
|
}
|
||||||
|
assert_eq!(
|
||||||
|
keys_in(&kernel).len(),
|
||||||
|
1 + template.len() + 1,
|
||||||
|
"the genesis key and one NFC key per position are held, no NFD key"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -181,6 +181,11 @@ impl WorldJournal {
|
||||||
self.commits.get(&command_id)
|
self.commits.get(&command_id)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Every commit the journal holds, in no particular order.
|
||||||
|
pub(super) fn commits(&self) -> impl Iterator<Item = &WorldCommit> {
|
||||||
|
self.commits.values()
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
pub(super) fn commit_count(&self) -> usize {
|
pub(super) fn commit_count(&self) -> usize {
|
||||||
self.commits.len()
|
self.commits.len()
|
||||||
|
|
@ -728,6 +733,55 @@ pub(super) fn verify_state_shape(state: &WorldState) -> Result<(), JournalError>
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Attitude: a holder and its target are canonical subjects, a delta is
|
||||||
|
// nonzero and bounded, a stamp is not from the future, and a rumour rests
|
||||||
|
// on a fact that exists. A trait row names a canonical subject, a civic
|
||||||
|
// trait name, and at least one real fact.
|
||||||
|
for (holder, held) in &state.attitudes {
|
||||||
|
let modifier_is_canonical = |key: &super::AttitudeKey, modifier: &super::AttitudeModifier| {
|
||||||
|
let toward_is_canonical = match &key.toward {
|
||||||
|
super::AttitudeToward::Subject(target) => {
|
||||||
|
state.subjects.contains_key(target) && target != holder
|
||||||
|
}
|
||||||
|
super::AttitudeToward::Trait(name) => super::patch::is_civic_name(&name.0),
|
||||||
|
};
|
||||||
|
let cause_is_canonical = match &key.cause {
|
||||||
|
super::AttitudeCause::Rumour { fact } => {
|
||||||
|
state.facts.contains_key(fact)
|
||||||
|
&& matches!(key.toward, super::AttitudeToward::Subject(_))
|
||||||
|
}
|
||||||
|
_ => true,
|
||||||
|
};
|
||||||
|
toward_is_canonical
|
||||||
|
&& cause_is_canonical
|
||||||
|
&& crate::attitude::is_valid_delta(modifier.delta)
|
||||||
|
&& crate::attitude::is_valid_decay(modifier.decay)
|
||||||
|
&& modifier.since <= state.now
|
||||||
|
};
|
||||||
|
if !state.subjects.contains_key(holder)
|
||||||
|
|| held.is_empty()
|
||||||
|
|| !held.iter().all(|(key, modifier)| modifier_is_canonical(key, modifier))
|
||||||
|
{
|
||||||
|
return Err(JournalError::Corrupt(
|
||||||
|
"an attitude row does not name a canonical holder, target, cause, and bounded delta"
|
||||||
|
.into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (subject_id, carried) in &state.traits {
|
||||||
|
if !state.subjects.contains_key(subject_id)
|
||||||
|
|| carried.is_empty()
|
||||||
|
|| carried.iter().any(|(name, evidence)| {
|
||||||
|
!super::patch::is_civic_name(&name.0)
|
||||||
|
|| evidence.is_empty()
|
||||||
|
|| !evidence.iter().all(|fact| state.facts.contains_key(fact))
|
||||||
|
})
|
||||||
|
{
|
||||||
|
return Err(JournalError::Corrupt(
|
||||||
|
"a trait row does not name a canonical subject, trait, and fact".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
if state
|
if state
|
||||||
.last_opportunity_at
|
.last_opportunity_at
|
||||||
.iter()
|
.iter()
|
||||||
|
|
@ -826,6 +880,17 @@ pub(super) fn verify_state_shape(state: &WorldState) -> Result<(), JournalError>
|
||||||
"one subject holds two overlapping jurisdictions of one kind".into(),
|
"one subject holds two overlapping jurisdictions of one kind".into(),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
let mut declared_keys = BTreeSet::new();
|
||||||
|
let no_held = BTreeSet::new();
|
||||||
|
for subject in state.subjects.values() {
|
||||||
|
if let Some(key) = &subject.import_key
|
||||||
|
&& super::patch::import_key_fault(key, &no_held, &mut declared_keys).is_some()
|
||||||
|
{
|
||||||
|
return Err(JournalError::Corrupt(
|
||||||
|
"subject import key is malformed or held by two subjects".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
let mut controller_ids = BTreeSet::new();
|
let mut controller_ids = BTreeSet::new();
|
||||||
for (subject_id, subject) in &state.subjects {
|
for (subject_id, subject) in &state.subjects {
|
||||||
if !super::patch::is_canonical_text(&subject.label) {
|
if !super::patch::is_canonical_text(&subject.label) {
|
||||||
|
|
@ -1107,8 +1172,11 @@ mod tests {
|
||||||
},
|
},
|
||||||
affordances: kernel_speak_grant(),
|
affordances: kernel_speak_grant(),
|
||||||
position: None,
|
position: None,
|
||||||
|
import_key: None,
|
||||||
}),
|
}),
|
||||||
scale_intent: WorldScaleIntentRef::default(),
|
scale_intent: WorldScaleIntentRef::default(),
|
||||||
|
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();
|
||||||
|
|
@ -1190,8 +1258,11 @@ mod tests {
|
||||||
},
|
},
|
||||||
affordances: kernel_speak_grant(),
|
affordances: kernel_speak_grant(),
|
||||||
position: None,
|
position: None,
|
||||||
|
import_key: None,
|
||||||
}),
|
}),
|
||||||
scale_intent: WorldScaleIntentRef::default(),
|
scale_intent: WorldScaleIntentRef::default(),
|
||||||
|
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();
|
||||||
|
|
@ -1220,6 +1291,7 @@ mod tests {
|
||||||
controller: NewController::OperationalAgent,
|
controller: NewController::OperationalAgent,
|
||||||
affordances: BTreeSet::from([speak_entry(&kernel)]),
|
affordances: BTreeSet::from([speak_entry(&kernel)]),
|
||||||
position: Some(Ref::Draft(DraftHandle::new("rhythm-road"))),
|
position: Some(Ref::Draft(DraftHandle::new("rhythm-road"))),
|
||||||
|
import_key: None,
|
||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
operations: Vec::new(),
|
operations: Vec::new(),
|
||||||
|
|
@ -1755,8 +1827,11 @@ mod tests {
|
||||||
controller: NewController::Human { principal: owner },
|
controller: NewController::Human { principal: owner },
|
||||||
affordances: kernel_speak_grant(),
|
affordances: kernel_speak_grant(),
|
||||||
position: None,
|
position: None,
|
||||||
|
import_key: None,
|
||||||
}),
|
}),
|
||||||
scale_intent: WorldScaleIntentRef::default(),
|
scale_intent: WorldScaleIntentRef::default(),
|
||||||
|
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();
|
||||||
|
|
@ -2964,4 +3039,118 @@ mod custody_tests {
|
||||||
"the chain digest answered for the authority check: {detail}"
|
"the chain digest answered for the authority check: {detail}"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Attitude replays exactly: a restart rebuilds the same modifiers, traits
|
||||||
|
/// and digest from the commits, and a row nobody's command wrote, whether
|
||||||
|
/// edited, planted, or re-sealed under a digest that agrees with it, stops
|
||||||
|
/// the history from recovering.
|
||||||
|
#[test]
|
||||||
|
fn attitude_replays_exactly_and_a_forged_row_fails_replay() {
|
||||||
|
use crate::attitude::{AttitudeBasisRef, AttitudeCause, AttitudeKey, AttitudeToward, AttitudeTowardRef, TraitName};
|
||||||
|
use crate::tests::{auth_principal, creation, operations, owner, speech_world, submit_owner};
|
||||||
|
use crate::{ComponentOp, Ref};
|
||||||
|
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let path = directory.path().join("world.cc");
|
||||||
|
let (mut kernel, _) =
|
||||||
|
WorldKernel::create(&path, creation(CommandId::new(), "Attitude"), &auth_principal(owner()))
|
||||||
|
.unwrap();
|
||||||
|
let (speech, _) = speech_world(&mut kernel);
|
||||||
|
let before = kernel.snapshot().unwrap();
|
||||||
|
submit_owner(
|
||||||
|
&mut kernel,
|
||||||
|
&before,
|
||||||
|
operations(vec![
|
||||||
|
ComponentOp::AdjustAttitude {
|
||||||
|
holder: Ref::Existing(speech.listener),
|
||||||
|
toward: Ref::Existing(speech.speaker),
|
||||||
|
delta: -30,
|
||||||
|
decay: None,
|
||||||
|
},
|
||||||
|
ComponentOp::DeclareTrait {
|
||||||
|
subject: Ref::Existing(speech.speaker),
|
||||||
|
name: TraitName("outlander".into()),
|
||||||
|
fact: Ref::Existing(speech.flood),
|
||||||
|
},
|
||||||
|
ComponentOp::DeclareAttitude {
|
||||||
|
holder: Ref::Existing(speech.listener),
|
||||||
|
toward: AttitudeTowardRef::Trait(TraitName("outlander".into())),
|
||||||
|
delta: -10,
|
||||||
|
basis: AttitudeBasisRef::Prejudice,
|
||||||
|
decay: None,
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
assert!(!kernel.state.attitudes.is_empty() && !kernel.state.traits.is_empty());
|
||||||
|
|
||||||
|
let rows = |state: &WorldState| -> Vec<CultCacheEnvelope> {
|
||||||
|
let mut rows: Vec<CultCacheEnvelope> = kernel
|
||||||
|
.journal
|
||||||
|
.commits
|
||||||
|
.values()
|
||||||
|
.map(|commit| {
|
||||||
|
envelope(COMMIT_ROW, COMMIT_SCHEMA, commit.command.id().key(), commit).unwrap()
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
rows.push(envelope(STATE_ROW, STATE_SCHEMA, state.world_id.key(), state).unwrap());
|
||||||
|
rows
|
||||||
|
};
|
||||||
|
let (_, recovered, _) = recover(rows(&kernel.state), None).expect("the honest history recovers");
|
||||||
|
assert_eq!(recovered, kernel.state);
|
||||||
|
assert_eq!(recovered.state_digest, kernel.state.state_digest);
|
||||||
|
|
||||||
|
let planted = AttitudeKey {
|
||||||
|
toward: AttitudeToward::Subject(speech.listener),
|
||||||
|
cause: AttitudeCause::Prejudice,
|
||||||
|
};
|
||||||
|
let forgeries: Vec<(&str, Box<dyn Fn(&mut WorldState)>)> = vec![
|
||||||
|
(
|
||||||
|
"a grievance edited",
|
||||||
|
Box::new(|state| {
|
||||||
|
let held = state.attitudes.get_mut(&speech.listener).unwrap();
|
||||||
|
held.values_mut().next().unwrap().delta = -90;
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"an attitude planted",
|
||||||
|
Box::new(move |state| {
|
||||||
|
state.attitudes.entry(speech.speaker).or_default().insert(
|
||||||
|
planted.clone(),
|
||||||
|
crate::AttitudeModifier {
|
||||||
|
delta: -50,
|
||||||
|
since: state.now,
|
||||||
|
decay: None,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"a grievance erased",
|
||||||
|
Box::new(|state| {
|
||||||
|
state.attitudes.clear();
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"a trait erased",
|
||||||
|
Box::new(|state| {
|
||||||
|
state.traits.clear();
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
for (name, forge) in forgeries {
|
||||||
|
let mut forged = kernel.state.clone();
|
||||||
|
forge(&mut forged);
|
||||||
|
assert!(
|
||||||
|
matches!(recover(rows(&forged), None), Err(JournalError::Corrupt(_))),
|
||||||
|
"{name}: a forged attitude row replayed"
|
||||||
|
);
|
||||||
|
// Re-sealed under a digest that agrees with the forgery.
|
||||||
|
forged.state_digest = crate::state_digest(&forged).unwrap();
|
||||||
|
assert!(
|
||||||
|
matches!(recover(rows(&forged), None), Err(JournalError::Corrupt(_))),
|
||||||
|
"{name}: a re-sealed forged attitude row replayed"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -52,7 +52,7 @@ impl Lens {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What kind of structure the lens reaches for.
|
/// 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",
|
||||||
|
|
|
||||||
|
|
@ -54,24 +54,41 @@
|
||||||
//! ```compile_fail,E0425
|
//! ```compile_fail,E0425
|
||||||
//! let _ = ghostlight::fixture_inference_output("prose", "receipt");
|
//! let _ = ghostlight::fixture_inference_output("prose", "receipt");
|
||||||
//! ```
|
//! ```
|
||||||
|
//!
|
||||||
|
//! ```compile_fail,E0599
|
||||||
|
//! fn no_lane_reads_it(port: &ghostlight::ControllerPort) {
|
||||||
|
//! let _ = port.hierarchy();
|
||||||
|
//! }
|
||||||
|
//! ```
|
||||||
|
|
||||||
mod action;
|
mod action;
|
||||||
|
mod aetheria;
|
||||||
|
mod attitude;
|
||||||
mod clock;
|
mod clock;
|
||||||
mod consumer;
|
mod consumer;
|
||||||
mod controllers;
|
mod controllers;
|
||||||
mod cover;
|
mod cover;
|
||||||
mod elaboration;
|
mod elaboration;
|
||||||
|
mod grammar;
|
||||||
|
mod hierarchy;
|
||||||
|
#[cfg(test)]
|
||||||
|
mod import_key_tests;
|
||||||
mod journal;
|
mod journal;
|
||||||
mod lens;
|
mod lens;
|
||||||
mod local_inference;
|
mod local_inference;
|
||||||
mod mailbox;
|
mod mailbox;
|
||||||
mod patch;
|
mod patch;
|
||||||
mod sdk_inference;
|
mod routed_inference;
|
||||||
mod table;
|
mod table;
|
||||||
mod tool_schema;
|
mod tool_schema;
|
||||||
mod vault;
|
mod vault;
|
||||||
|
mod verse;
|
||||||
|
mod wave;
|
||||||
|
|
||||||
pub(crate) use action::ActionMismatch;
|
pub(crate) use action::ActionMismatch;
|
||||||
|
pub(crate) use attitude::{
|
||||||
|
AttitudeCause, AttitudeKey, AttitudeModifier, AttitudeToward, TraitName,
|
||||||
|
};
|
||||||
pub(crate) use clock::Motion;
|
pub(crate) use clock::Motion;
|
||||||
pub use clock::{FictionalMinutes, TickMinutes};
|
pub use clock::{FictionalMinutes, TickMinutes};
|
||||||
pub use consumer::{
|
pub use consumer::{
|
||||||
|
|
@ -80,23 +97,39 @@ pub use consumer::{
|
||||||
};
|
};
|
||||||
pub use controllers::{
|
pub use controllers::{
|
||||||
CONTROLLER_WORK_SCHEMA, CellRun, ConnectorBinding, ControllerError, ControllerModels,
|
CONTROLLER_WORK_SCHEMA, CellRun, ConnectorBinding, ControllerError, ControllerModels,
|
||||||
|
ControllerOpenError,
|
||||||
ControllerNeed, ControllerPendingReason, ControllerRunner, ControllerWork,
|
ControllerNeed, ControllerPendingReason, ControllerRunner, ControllerWork,
|
||||||
ControllerWorkCustody, ControllerWorkLookup, ControllerWorkStore, ControllerWorkStoreError,
|
ControllerWorkCustody, ControllerWorkLookup, ControllerWorkStore, ControllerWorkStoreError,
|
||||||
ControllerWorkWrite,
|
ControllerWorkWrite,
|
||||||
GroupedCheckpoint, InferenceEvent, InferenceFault, InferenceFaultDisposition, InferenceOutput,
|
GroupedCheckpoint, InferenceEvent, InferenceFault, InferenceFaultClass, InferenceFaultDisposition, InferenceOutput,
|
||||||
InferencePort,
|
InferencePort,
|
||||||
InferencePurpose, InferenceRequest, NarrativeCheckpoint, NarrativeRun, OperationalCheckpoint,
|
InferencePurpose, InferenceRequest, NarrativeCheckpoint, NarrativeRun, OperationalCheckpoint,
|
||||||
OperationalRun, PersonaLane, PreparedInference, SubmissionDisposition, ToolResultOracle,
|
OperationalRun, PersonaLane, PreparedInference, SubmissionDisposition, TokenUsage,
|
||||||
TracingInferencePort, open_controller_work, open_inference,
|
TracingInferencePort, open_controller_work, open_inference,
|
||||||
};
|
};
|
||||||
pub(crate) use cover::{CellId, Constituent, Resolution};
|
pub(crate) use cover::{CellId, Constituent, Resolution};
|
||||||
|
pub use aetheria::{
|
||||||
|
AetheriaCatalog, AetheriaFaction, CatalogReadError, VerbRule, read_aetheria_catalog,
|
||||||
|
};
|
||||||
pub use cover::{AgencyGraph, Cell, Cover, CoverBudget, CoverBudgetError, TickIndex, derive_cover};
|
pub use cover::{AgencyGraph, Cell, Cover, CoverBudget, CoverBudgetError, TickIndex, derive_cover};
|
||||||
|
pub use hierarchy::{Hierarchy, Node, NodeAnchor, NodeId};
|
||||||
|
pub use wave::{
|
||||||
|
Deferral, DeferredNode, Focus, FrozenCell, GestaltKnobs, GestaltKnobsError, NodeOutcome, NodeReport,
|
||||||
|
NodeTurn, Refusal, RefusalReason, UnattributedCall, Wave, WaveClock, WaveOutcome, WaveStop,
|
||||||
|
act_line, acts_since, deferred_nodes, node_label, node_reports, plan_wave, run_frozen_cells,
|
||||||
|
};
|
||||||
pub use elaboration::{
|
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::{
|
||||||
|
GrammarBinding, GrammarError, GrammarIdentity, GrammarReferentKind, GrammarRole, GrammarVerb,
|
||||||
|
RenderPath,
|
||||||
};
|
};
|
||||||
pub use lens::{Lens, LensWeights};
|
pub use lens::{Lens, LensWeights};
|
||||||
pub use local_inference::{DEFAULT_LOCAL_MODEL_PREFIX, LocalBinding};
|
pub use local_inference::{DEFAULT_HOSTED_MODEL_PREFIX, DEFAULT_LOCAL_MODEL_PREFIX, HostedBinding, LocalBinding};
|
||||||
|
#[cfg(feature = "test-support")]
|
||||||
|
pub use local_inference::open_local_port_with_timeout;
|
||||||
pub(crate) use mailbox::ElaborationPort;
|
pub(crate) use mailbox::ElaborationPort;
|
||||||
pub use mailbox::{ConsumerPort, ControllerPort, MailboxError, PlayPort, SeedPort, WorldMailbox};
|
pub use mailbox::{ConsumerPort, ControllerPort, MailboxError, PlayPort, SeedPort, WorldMailbox};
|
||||||
pub use patch::{
|
pub use patch::{
|
||||||
|
|
@ -111,6 +144,7 @@ pub(crate) use patch::{
|
||||||
PersonaMaterial, Position, PressureMagnitude, PressureSource, Quantity, Reach,
|
PersonaMaterial, Position, PressureMagnitude, PressureSource, Quantity, Reach,
|
||||||
SubjectDeclaration, WorldScaleIntent, WorldScaleIntentRef,
|
SubjectDeclaration, WorldScaleIntent, WorldScaleIntentRef,
|
||||||
};
|
};
|
||||||
|
pub use patch::ImportKey;
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
use patch::{
|
use patch::{
|
||||||
AffordanceDeclaration, AudienceRef, AudienceSpec, ChannelDeclaration, ComponentOp,
|
AffordanceDeclaration, AudienceRef, AudienceSpec, ChannelDeclaration, ComponentOp,
|
||||||
|
|
@ -121,13 +155,23 @@ pub(crate) use patch::{
|
||||||
AffordanceKindName, AuthorityGrantRef, AuthorityKindName, AuthorityTargetRef, ComponentOpKind,
|
AffordanceKindName, AuthorityGrantRef, AuthorityKindName, AuthorityTargetRef, ComponentOpKind,
|
||||||
EffectSlot, OutcomeBand, Precondition, RoleSpec,
|
EffectSlot, OutcomeBand, Precondition, RoleSpec,
|
||||||
};
|
};
|
||||||
pub use sdk_inference::{DEFAULT_SDK_MODEL_PREFIX, SdkBinding};
|
|
||||||
pub use table::{
|
pub use table::{
|
||||||
DecodedBatch, PatchSite, TableError, actor_tools, authoring_tools, decode_actor_call,
|
DecodedBatch, PatchSite, TableError, actor_tools, authoring_tools, decode_actor_call,
|
||||||
decode_authoring_call, decode_authoring_calls, describe_refusal, describe_refusal_to_actor,
|
decode_authoring_call, decode_authoring_calls, describe_refusal, describe_refusal_to_actor,
|
||||||
id_text, id_text_matches, table_view,
|
handle_for, id_text, id_text_matches, table_view,
|
||||||
|
};
|
||||||
|
pub use vault::{
|
||||||
|
ImportOutcome, SnapshotId, VAULT_PROFILE_SCHEMA, VAULT_SNAPSHOT_SCHEMA, VaultError,
|
||||||
|
VaultEra, VaultEvidenceSource, VaultProfile, VaultSnapshot, production_eras, production_profile, production_vault_names,
|
||||||
|
};
|
||||||
|
pub use verse::{
|
||||||
|
CALL_RECORD_SCHEMA, CallRecordError, CallRecordStore, CreateVerseWorldIntent, Lane, LaneTokens,
|
||||||
|
NodeSpend, ProviderCallRecord, WaveSpend,
|
||||||
|
RUN_RECORD_SCHEMA, RecordedKnobs, RecordingInferencePort, RunClaim,
|
||||||
|
ReplayInferencePort, RunField, RunId, RunOutcome, RunStart, RunStatus, TickCheckpoint,
|
||||||
|
TickReport, VerseGenesisError, VerseRunConfig, VerseRunError, VerseRunRecord, VerseRunStore,
|
||||||
|
call_run_id, run_manual,
|
||||||
};
|
};
|
||||||
pub use vault::{VaultError, VaultEvidenceSource};
|
|
||||||
use patch::{EdgeRecord, EntityRecord, LedgerDelta, ResolvedOp, ResolvedPatch};
|
use patch::{EdgeRecord, EntityRecord, LedgerDelta, ResolvedOp, ResolvedPatch};
|
||||||
|
|
||||||
use chrono::{DateTime, Utc};
|
use chrono::{DateTime, Utc};
|
||||||
|
|
@ -423,6 +467,24 @@ struct CreateWorld {
|
||||||
/// The world's flavor as genesis writes it. `SetLensWeights` may replace
|
/// The world's flavor as genesis writes it. `SetLensWeights` may replace
|
||||||
/// it later; this command carries what the world began with.
|
/// it later; this command carries what the world began with.
|
||||||
lens_weights: LensWeights,
|
lens_weights: LensWeights,
|
||||||
|
/// The grammar the world is bound to for its whole life, or none for an
|
||||||
|
/// open-catalog world. Authored here and nowhere else: genesis installs it.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
grammar: Option<GrammarBinding>,
|
||||||
|
/// The era the world is pinned to, authored here and nowhere else: no
|
||||||
|
/// `CommandBody` carries a `WorldEra`, so it is write-once by command
|
||||||
|
/// shape, as `scale_intent` is.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
era: Option<WorldEra>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The period of its lore a world is set in. Authored at genesis by the
|
||||||
|
/// consumer that knows what periods its lore has, and never replaced.
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||||
|
pub struct WorldEra {
|
||||||
|
pub id: String,
|
||||||
|
pub label: String,
|
||||||
|
pub description: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Unattributed creation intent. World ingress derives ownership, controller
|
/// Unattributed creation intent. World ingress derives ownership, controller
|
||||||
|
|
@ -447,6 +509,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
|
||||||
|
|
@ -707,6 +772,10 @@ pub enum CommandBody {
|
||||||
struct SubjectState {
|
struct SubjectState {
|
||||||
label: String,
|
label: String,
|
||||||
kind: SubjectKind,
|
kind: SubjectKind,
|
||||||
|
/// Written only when a subject declaration is resolved; absent from a
|
||||||
|
/// subject nobody imported, so its digests are unchanged.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
import_key: Option<ImportKey>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||||
|
|
@ -826,6 +895,15 @@ struct WorldState {
|
||||||
/// Authored at creation and never mutated; the one prose the world says
|
/// Authored at creation and never mutated; the one prose the world says
|
||||||
/// about itself, projected as guidance to every lane.
|
/// about itself, projected as guidance to every lane.
|
||||||
brief: String,
|
brief: String,
|
||||||
|
/// Bound by genesis and never written again; absent from a world with no
|
||||||
|
/// grammar, so such a world's state and digests are what they were before
|
||||||
|
/// grammars existed.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
grammar: Option<GrammarBinding>,
|
||||||
|
/// Pinned by genesis and never written again; absent from a world with no
|
||||||
|
/// era, whose state and digests are what they were before eras existed.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
era: Option<WorldEra>,
|
||||||
draft_approvals: BTreeSet<PrincipalId>,
|
draft_approvals: BTreeSet<PrincipalId>,
|
||||||
subjects: BTreeMap<SubjectId, SubjectState>,
|
subjects: BTreeMap<SubjectId, SubjectState>,
|
||||||
entities: BTreeMap<EntityId, EntityRecord>,
|
entities: BTreeMap<EntityId, EntityRecord>,
|
||||||
|
|
@ -871,6 +949,19 @@ struct WorldState {
|
||||||
/// Pressure *on* each subject, keyed target-major then source. Never empty
|
/// Pressure *on* each subject, keyed target-major then source. Never empty
|
||||||
/// for a present key; no stored zero magnitude.
|
/// for a present key; no stored zero magnitude.
|
||||||
pressures: BTreeMap<SubjectId, BTreeMap<PressureSource, PressureMagnitude>>,
|
pressures: BTreeMap<SubjectId, BTreeMap<PressureSource, PressureMagnitude>>,
|
||||||
|
/// How each subject regards others: sourced modifiers, never a stored
|
||||||
|
/// opinion (`attitude::opinion` derives it). Never empty for a present key;
|
||||||
|
/// no stored zero delta. Outside every scope digest: attitude constrains no
|
||||||
|
/// precondition. Absent from a world that has none, so such a world's state
|
||||||
|
/// and digests are what they were before attitude existed.
|
||||||
|
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||||
|
attitudes: BTreeMap<SubjectId, BTreeMap<AttitudeKey, AttitudeModifier>>,
|
||||||
|
/// The facts the world declares as evidence that a subject carries a trait:
|
||||||
|
/// what a prejudice reads, since a trait modifier applies to a subject only
|
||||||
|
/// while its holder knows one of these. Never empty for a present key.
|
||||||
|
/// Absent when empty, for the same reason as `attitudes`.
|
||||||
|
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||||
|
traits: BTreeMap<SubjectId, BTreeMap<TraitName, BTreeSet<EntityId>>>,
|
||||||
/// When each subject was last given a decision opportunity it consumed.
|
/// When each subject was last given a decision opportunity it consumed.
|
||||||
/// Absence means never. The debt term of the attention order and nothing
|
/// Absence means never. The debt term of the attention order and nothing
|
||||||
/// else.
|
/// else.
|
||||||
|
|
@ -991,6 +1082,8 @@ pub struct SubjectSnapshot {
|
||||||
pub id: SubjectId,
|
pub id: SubjectId,
|
||||||
pub label: String,
|
pub label: String,
|
||||||
pub kind: SubjectKind,
|
pub kind: SubjectKind,
|
||||||
|
/// The Aetheria record this subject was imported from, if it was.
|
||||||
|
pub import_key: Option<ImportKey>,
|
||||||
/// Absent for an externally controlled mirror, which has no controller and
|
/// Absent for an externally controlled mirror, which has no controller and
|
||||||
/// no turn. Every reader fails closed on `None`; none gets a default.
|
/// no turn. Every reader fails closed on `None`; none gets a default.
|
||||||
pub(crate) controller_id: Option<ControllerId>,
|
pub(crate) controller_id: Option<ControllerId>,
|
||||||
|
|
@ -1032,6 +1125,11 @@ pub struct SubjectSnapshot {
|
||||||
/// subject's state, and the actor already sees the commitment that produced
|
/// subject's state, and the actor already sees the commitment that produced
|
||||||
/// it.
|
/// it.
|
||||||
pub(crate) pressures: Vec<PressureSnapshot>,
|
pub(crate) pressures: Vec<PressureSnapshot>,
|
||||||
|
/// How this subject regards each subject it has an opinion of, derived by
|
||||||
|
/// `attitude::opinion` at snapshot time: never stored, so there is one
|
||||||
|
/// answer for the Dungeon Master's table, a Persona's own view, and the
|
||||||
|
/// narrator. View-only, covered by no digest of its own.
|
||||||
|
pub(crate) opinions: Vec<OpinionSnapshot>,
|
||||||
/// This subject's own dependencies, lowered from `components.dependencies`
|
/// This subject's own dependencies, lowered from `components.dependencies`
|
||||||
/// (private to this module) so the play table's omniscient view can print
|
/// (private to this module) so the play table's omniscient view can print
|
||||||
/// what a `release` may name without reaching into `ScopeComponents`
|
/// what a `release` may name without reaching into `ScopeComponents`
|
||||||
|
|
@ -1071,6 +1169,17 @@ pub(crate) struct PressureSnapshot {
|
||||||
pub(crate) magnitude: PressureMagnitude,
|
pub(crate) magnitude: PressureMagnitude,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// One subject's derived regard for another, with its strongest causes. A trait
|
||||||
|
/// prejudice appears only once the holder knows the subject carries the trait.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub(crate) struct OpinionSnapshot {
|
||||||
|
pub(crate) toward: SubjectId,
|
||||||
|
/// Clamped to `-MAX_ATTITUDE..=MAX_ATTITUDE`.
|
||||||
|
pub(crate) total: i32,
|
||||||
|
/// At most `OPINION_CAUSES_SHOWN`, strongest first.
|
||||||
|
pub(crate) causes: Vec<attitude::OpinionCause>,
|
||||||
|
}
|
||||||
|
|
||||||
/// What a subject knows of one fact. `standing` carries no `EvidenceRef`: a
|
/// What a subject knows of one fact. `standing` carries no `EvidenceRef`: a
|
||||||
/// receipt is non-fictional provenance and never enters a subject-facing
|
/// receipt is non-fictional provenance and never enters a subject-facing
|
||||||
/// surface, so a subject learns *that* a fact is canonical and never which
|
/// surface, so a subject learns *that* a fact is canonical and never which
|
||||||
|
|
@ -1133,6 +1242,9 @@ pub(crate) struct ForumSnapshot {
|
||||||
pub struct AffordanceSnapshot {
|
pub struct AffordanceSnapshot {
|
||||||
pub id: AffordanceId,
|
pub id: AffordanceId,
|
||||||
pub entry: Affordance,
|
pub entry: Affordance,
|
||||||
|
/// Derived from the world's grammar by this entry's kind; none when the
|
||||||
|
/// world has no grammar.
|
||||||
|
pub render_path: Option<RenderPath>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
|
@ -1195,6 +1307,10 @@ 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.
|
||||||
|
pub grammar: Option<GrammarIdentity>,
|
||||||
pub draft_approvals: BTreeSet<PrincipalId>,
|
pub draft_approvals: BTreeSet<PrincipalId>,
|
||||||
pub required_approvers: BTreeSet<PrincipalId>,
|
pub required_approvers: BTreeSet<PrincipalId>,
|
||||||
pub subjects: Vec<SubjectSnapshot>,
|
pub subjects: Vec<SubjectSnapshot>,
|
||||||
|
|
@ -1226,6 +1342,63 @@ pub struct WorldSnapshot {
|
||||||
pub last_commit_digest: Option<String>,
|
pub last_commit_digest: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl WorldSnapshot {
|
||||||
|
/// The place a subject stands in, for the owner's own surfaces; no
|
||||||
|
/// subject-facing lane reads this.
|
||||||
|
pub fn place_of(&self, subject: SubjectId) -> Option<EntityId> {
|
||||||
|
self.subjects.iter().find(|candidate| candidate.id == subject)?.position
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The label of the place a subject stands in, for the owner's own
|
||||||
|
/// surfaces and tests; no subject-facing lane reads this.
|
||||||
|
pub fn standing_place(&self, subject: SubjectId) -> Option<&str> {
|
||||||
|
let position = self.place_of(subject)?;
|
||||||
|
self.places.iter().find(|place| place.id == position).map(|place| place.label.as_str())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The live subjects with a controller other than a human's that stand in
|
||||||
|
/// the same place as `subject`, ascending by id; `subject` itself is never
|
||||||
|
/// among them. For the owner's own surfaces (the Dungeon's room-level
|
||||||
|
/// reaction derives its audience here): no controller lane reads it, since
|
||||||
|
/// one subject must not learn who else stands beside it from a list the
|
||||||
|
/// kernel built for the table.
|
||||||
|
pub fn co_located(&self, subject: SubjectId) -> Vec<SubjectId> {
|
||||||
|
let Some(position) = self
|
||||||
|
.subjects
|
||||||
|
.iter()
|
||||||
|
.find(|candidate| candidate.id == subject)
|
||||||
|
.and_then(|candidate| candidate.position)
|
||||||
|
else {
|
||||||
|
return Vec::new();
|
||||||
|
};
|
||||||
|
let mut present: Vec<SubjectId> = self
|
||||||
|
.subjects
|
||||||
|
.iter()
|
||||||
|
.filter(|other| {
|
||||||
|
other.id != subject
|
||||||
|
&& !other.retired
|
||||||
|
&& other.position == Some(position)
|
||||||
|
&& matches!(other.controller_mode, Some(mode) if mode != ControllerMode::Human)
|
||||||
|
})
|
||||||
|
.map(|other| other.id)
|
||||||
|
.collect();
|
||||||
|
present.sort();
|
||||||
|
present
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What every lane reads as the world's guidance: the era line, then the
|
||||||
|
/// owner's brief verbatim, either omitted when empty. Derived on every
|
||||||
|
/// read; no prompt reads `brief` directly.
|
||||||
|
pub fn guidance(&self) -> String {
|
||||||
|
let era = self
|
||||||
|
.era
|
||||||
|
.as_ref()
|
||||||
|
.map(|era| format!("Era: {}. {}", era.label, era.description));
|
||||||
|
let brief = (!self.brief.is_empty()).then(|| self.brief.clone());
|
||||||
|
[era, brief].into_iter().flatten().collect::<Vec<_>>().join("\n")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// One committed act as the human operator's story feed reads it. It is the
|
/// 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.
|
||||||
|
|
@ -1236,6 +1409,21 @@ pub struct OperatorEvent {
|
||||||
pub speaker_label: String,
|
pub speaker_label: String,
|
||||||
pub speech: Option<Statement>,
|
pub speech: Option<Statement>,
|
||||||
pub display: Option<Statement>,
|
pub display: Option<Statement>,
|
||||||
|
/// The affordance kind the act exercised.
|
||||||
|
pub verb: String,
|
||||||
|
/// How the world's grammar renders that verb; none in a world with no
|
||||||
|
/// grammar.
|
||||||
|
pub render_path: Option<RenderPath>,
|
||||||
|
/// What the act bound each of the verb's roles to, in the invocation's
|
||||||
|
/// order.
|
||||||
|
pub roles: Vec<BoundRole>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One role an act bound, with the label of what it was bound to.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct BoundRole {
|
||||||
|
pub role: String,
|
||||||
|
pub target: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
|
@ -1419,11 +1607,23 @@ 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();
|
||||||
let resolved = patch::resolve_patch(
|
let resolved = patch::resolve_patch(
|
||||||
&WorldState::empty(world_id, input.owner.clone(), title.clone()),
|
&WorldState::empty(
|
||||||
|
world_id,
|
||||||
|
input.owner.clone(),
|
||||||
|
title.clone(),
|
||||||
|
input.grammar.clone(),
|
||||||
|
),
|
||||||
input.id,
|
input.id,
|
||||||
&input.patch,
|
&input.patch,
|
||||||
Some(&input.scale_intent),
|
Some(&input.scale_intent),
|
||||||
|
|
@ -1521,7 +1721,43 @@ impl WorldKernel {
|
||||||
/// no consumer may read in full would be a loaded gun with a comment on it.
|
/// no consumer may read in full would be a loaded gun with a comment on it.
|
||||||
fn operator_log(&self) -> Result<Vec<OperatorEvent>, KernelError> {
|
fn operator_log(&self) -> Result<Vec<OperatorEvent>, KernelError> {
|
||||||
self.journal.ensure_healthy()?;
|
self.journal.ensure_healthy()?;
|
||||||
operator_log(&self.state)
|
// An event records what the world did; the invocation, which names the
|
||||||
|
// bound roles, lives on the commit that produced it.
|
||||||
|
let invocations: BTreeMap<EventId, &DecisionInvocation> = self
|
||||||
|
.journal
|
||||||
|
.commits()
|
||||||
|
.filter_map(|commit| match &commit.effect {
|
||||||
|
WorldEffect::DecisionExercised {
|
||||||
|
invocation, event, ..
|
||||||
|
} => Some((event.id, invocation)),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
operator_log(&self.state, &invocations)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The tick driver's opportunity list, in the same order a snapshot
|
||||||
|
/// carries it. Separate from `snapshot` for the reason `agency_graph` is:
|
||||||
|
/// only the tick driver reads it.
|
||||||
|
fn opportunities(&self) -> Result<Vec<DecisionOpportunity>, KernelError> {
|
||||||
|
self.journal.ensure_healthy()?;
|
||||||
|
Ok(order_opportunities(
|
||||||
|
&self.state,
|
||||||
|
derive_opportunities(&self.state)?,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How many clock advances the world has committed: the next tick's
|
||||||
|
/// ordinal, held by the world and read from its journal. Separate from
|
||||||
|
/// `snapshot` for the reason `opportunities` is: only the tick driver
|
||||||
|
/// reads it.
|
||||||
|
fn clock_advances(&self) -> Result<u64, KernelError> {
|
||||||
|
self.journal.ensure_healthy()?;
|
||||||
|
Ok(self
|
||||||
|
.journal
|
||||||
|
.commits()
|
||||||
|
.filter(|commit| matches!(commit.effect, WorldEffect::TimeAdvanced { .. }))
|
||||||
|
.count() as u64)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The scheduler's adjacency projection. Separate from `snapshot` for the
|
/// The scheduler's adjacency projection. Separate from `snapshot` for the
|
||||||
|
|
@ -1533,6 +1769,14 @@ impl WorldKernel {
|
||||||
Ok(agency_graph(&self.state))
|
Ok(agency_graph(&self.state))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The gestalt hierarchy. Separate from `snapshot` for the reason
|
||||||
|
/// `agency_graph` is: it is wider than any subject view, so a field on
|
||||||
|
/// `WorldSnapshot` would be reachable from every prompt builder.
|
||||||
|
fn hierarchy(&self) -> Result<Hierarchy, KernelError> {
|
||||||
|
self.journal.ensure_healthy()?;
|
||||||
|
Ok(hierarchy::derive_hierarchy(&self.state))
|
||||||
|
}
|
||||||
|
|
||||||
fn submit(
|
fn submit(
|
||||||
&mut self,
|
&mut self,
|
||||||
command: CommandEnvelope,
|
command: CommandEnvelope,
|
||||||
|
|
@ -1894,7 +2138,12 @@ impl WorldState {
|
||||||
/// The world before any structure. Genesis resolves its own patch against
|
/// The world before any structure. Genesis resolves its own patch against
|
||||||
/// this value, so the genesis lane and `AdmitPatch` share one resolver
|
/// this value, so the genesis lane and `AdmitPatch` share one resolver
|
||||||
/// signature instead of hand-passing empty partitions.
|
/// signature instead of hand-passing empty partitions.
|
||||||
fn empty(world_id: WorldId, owner: PrincipalId, title: String) -> Self {
|
fn empty(
|
||||||
|
world_id: WorldId,
|
||||||
|
owner: PrincipalId,
|
||||||
|
title: String,
|
||||||
|
grammar: Option<GrammarBinding>,
|
||||||
|
) -> Self {
|
||||||
Self {
|
Self {
|
||||||
schema: STATE_SCHEMA.into(),
|
schema: STATE_SCHEMA.into(),
|
||||||
world_id,
|
world_id,
|
||||||
|
|
@ -1903,6 +2152,8 @@ impl WorldState {
|
||||||
owner,
|
owner,
|
||||||
title,
|
title,
|
||||||
brief: String::new(),
|
brief: String::new(),
|
||||||
|
grammar,
|
||||||
|
era: None,
|
||||||
draft_approvals: BTreeSet::new(),
|
draft_approvals: BTreeSet::new(),
|
||||||
subjects: BTreeMap::new(),
|
subjects: BTreeMap::new(),
|
||||||
entities: BTreeMap::new(),
|
entities: BTreeMap::new(),
|
||||||
|
|
@ -1919,6 +2170,8 @@ impl WorldState {
|
||||||
commitments: BTreeMap::new(),
|
commitments: BTreeMap::new(),
|
||||||
persona_material: BTreeMap::new(),
|
persona_material: BTreeMap::new(),
|
||||||
pressures: BTreeMap::new(),
|
pressures: BTreeMap::new(),
|
||||||
|
attitudes: BTreeMap::new(),
|
||||||
|
traits: BTreeMap::new(),
|
||||||
last_opportunity_at: BTreeMap::new(),
|
last_opportunity_at: BTreeMap::new(),
|
||||||
now: FictionalMinutes::default(),
|
now: FictionalMinutes::default(),
|
||||||
scale_intent: WorldScaleIntent::default(),
|
scale_intent: WorldScaleIntent::default(),
|
||||||
|
|
@ -1960,8 +2213,9 @@ impl WorldState {
|
||||||
// The same re-derive-and-compare that `apply_committed_command` runs for
|
// The same re-derive-and-compare that `apply_committed_command` runs for
|
||||||
// every other command. Deterministic allocation is what lets one
|
// every other command. Deterministic allocation is what lets one
|
||||||
// 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());
|
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,
|
||||||
|
|
@ -2069,6 +2323,18 @@ fn admit_resolved(
|
||||||
.filter_map(ControllerAssignment::id)
|
.filter_map(ControllerAssignment::id)
|
||||||
.collect();
|
.collect();
|
||||||
for entry in &resolved.affordances {
|
for entry in &resolved.affordances {
|
||||||
|
// The catalog's only writer holds the same grammar check the resolver
|
||||||
|
// runs, so an effect resolved elsewhere cannot install an entry the
|
||||||
|
// bound grammar refuses.
|
||||||
|
if state.grammar.as_ref().is_some_and(|grammar| {
|
||||||
|
grammar
|
||||||
|
.refusal(&entry.affordance.kind, &entry.affordance.roles)
|
||||||
|
.is_some()
|
||||||
|
}) {
|
||||||
|
return Err(KernelError::Invariant(
|
||||||
|
"admitted affordance is outside the bound grammar".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
if state
|
if state
|
||||||
.affordance_catalog
|
.affordance_catalog
|
||||||
.insert(entry.affordance_id, entry.affordance.clone())
|
.insert(entry.affordance_id, entry.affordance.clone())
|
||||||
|
|
@ -2079,6 +2345,21 @@ fn admit_resolved(
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// The subjects map's only writer holds the same injectivity the resolver
|
||||||
|
// checks, decided by the same function.
|
||||||
|
{
|
||||||
|
let held = patch::held_import_keys(state.subjects.values());
|
||||||
|
let mut declared = BTreeSet::new();
|
||||||
|
for subject in &resolved.subjects {
|
||||||
|
if let Some(key) = &subject.subject.import_key
|
||||||
|
&& patch::import_key_fault(key, &held, &mut declared).is_some()
|
||||||
|
{
|
||||||
|
return Err(KernelError::Invariant(
|
||||||
|
"admitted subject's import key is malformed, held or repeated".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
for subject in &resolved.subjects {
|
for subject in &resolved.subjects {
|
||||||
let scope = DecisionScope {
|
let scope = DecisionScope {
|
||||||
subject_id: subject.subject_id,
|
subject_id: subject.subject_id,
|
||||||
|
|
@ -3089,6 +3370,50 @@ fn apply_operation(
|
||||||
}
|
}
|
||||||
set_pressure(state, *target, *source, 0);
|
set_pressure(state, *target, *source, 0);
|
||||||
}
|
}
|
||||||
|
ResolvedOp::AdjustAttitude {
|
||||||
|
holder,
|
||||||
|
key,
|
||||||
|
delta,
|
||||||
|
decay,
|
||||||
|
} => {
|
||||||
|
let regards_live = match &key.toward {
|
||||||
|
AttitudeToward::Subject(target) => state.subjects.contains_key(target),
|
||||||
|
AttitudeToward::Trait(name) => patch::is_civic_name(&name.0),
|
||||||
|
};
|
||||||
|
let rests_on_known = match &key.cause {
|
||||||
|
AttitudeCause::Rumour { fact } => state.facts.contains_key(fact),
|
||||||
|
_ => true,
|
||||||
|
};
|
||||||
|
if !state.subjects.contains_key(holder)
|
||||||
|
|| !regards_live
|
||||||
|
|| !rests_on_known
|
||||||
|
|| !attitude::is_valid_delta(*delta)
|
||||||
|
|| !attitude::is_valid_decay(*decay)
|
||||||
|
|| key.toward == AttitudeToward::Subject(*holder)
|
||||||
|
{
|
||||||
|
return Err(unknown());
|
||||||
|
}
|
||||||
|
attitude::adjust(state, *holder, key.clone(), *delta, *decay);
|
||||||
|
}
|
||||||
|
ResolvedOp::DeclareTrait {
|
||||||
|
subject,
|
||||||
|
name,
|
||||||
|
fact,
|
||||||
|
} => {
|
||||||
|
if !state.subjects.contains_key(subject)
|
||||||
|
|| !state.facts.contains_key(fact)
|
||||||
|
|| !patch::is_civic_name(&name.0)
|
||||||
|
{
|
||||||
|
return Err(unknown());
|
||||||
|
}
|
||||||
|
state
|
||||||
|
.traits
|
||||||
|
.entry(*subject)
|
||||||
|
.or_default()
|
||||||
|
.entry(name.clone())
|
||||||
|
.or_default()
|
||||||
|
.insert(*fact);
|
||||||
|
}
|
||||||
ResolvedOp::Retire { subject } => {
|
ResolvedOp::Retire { subject } => {
|
||||||
let scope = DecisionScope {
|
let scope = DecisionScope {
|
||||||
subject_id: *subject,
|
subject_id: *subject,
|
||||||
|
|
@ -3663,7 +3988,10 @@ fn scope_components(state: &WorldState, subject_id: SubjectId) -> ScopeComponent
|
||||||
/// The human operator's story feed, derived from the causal record. The events
|
/// The human operator's story feed, derived from the causal record. The events
|
||||||
/// log is not a perception surface: `knowledge` is the sole answer to what a
|
/// log is not a perception surface: `knowledge` is the sole answer to what a
|
||||||
/// subject may act on and what its projection may contain.
|
/// subject may act on and what its projection may contain.
|
||||||
fn operator_log(state: &WorldState) -> Result<Vec<OperatorEvent>, KernelError> {
|
fn operator_log(
|
||||||
|
state: &WorldState,
|
||||||
|
invocations: &BTreeMap<EventId, &DecisionInvocation>,
|
||||||
|
) -> Result<Vec<OperatorEvent>, KernelError> {
|
||||||
state
|
state
|
||||||
.events
|
.events
|
||||||
.iter()
|
.iter()
|
||||||
|
|
@ -3672,6 +4000,30 @@ fn operator_log(state: &WorldState) -> Result<Vec<OperatorEvent>, KernelError> {
|
||||||
.subjects
|
.subjects
|
||||||
.get(&event.scope.subject_id)
|
.get(&event.scope.subject_id)
|
||||||
.ok_or_else(|| KernelError::Invariant("event names no live subject".into()))?;
|
.ok_or_else(|| KernelError::Invariant("event names no live subject".into()))?;
|
||||||
|
let invocation = invocations.get(&event.id).ok_or_else(|| {
|
||||||
|
KernelError::Invariant("event has no committed invocation".into())
|
||||||
|
})?;
|
||||||
|
let entry = state
|
||||||
|
.affordance_catalog
|
||||||
|
.get(&event.affordance)
|
||||||
|
.ok_or_else(|| KernelError::Invariant("event names no catalog entry".into()))?;
|
||||||
|
let roles = invocation
|
||||||
|
.bindings
|
||||||
|
.iter()
|
||||||
|
.map(|binding| {
|
||||||
|
let label = match binding.target {
|
||||||
|
Target::Subject(id) => state.subjects.get(&id).map(|s| s.label.clone()),
|
||||||
|
Target::Entity(id) => state.entities.get(&id).map(|e| e.label.clone()),
|
||||||
|
Target::Edge(id) => state.edges.contains_key(&id).then(|| "edge".to_owned()),
|
||||||
|
};
|
||||||
|
label
|
||||||
|
.map(|target| BoundRole {
|
||||||
|
role: binding.role.0.clone(),
|
||||||
|
target,
|
||||||
|
})
|
||||||
|
.ok_or_else(|| KernelError::Invariant("event binds no live referent".into()))
|
||||||
|
})
|
||||||
|
.collect::<Result<Vec<_>, _>>()?;
|
||||||
Ok(OperatorEvent {
|
Ok(OperatorEvent {
|
||||||
revision: event.revision,
|
revision: event.revision,
|
||||||
speaker: event.scope.subject_id,
|
speaker: event.scope.subject_id,
|
||||||
|
|
@ -3684,6 +4036,13 @@ fn operator_log(state: &WorldState) -> Result<Vec<OperatorEvent>, KernelError> {
|
||||||
.display
|
.display
|
||||||
.and_then(|fact| state.facts.get(&fact))
|
.and_then(|fact| state.facts.get(&fact))
|
||||||
.map(|record| record.statement.clone()),
|
.map(|record| record.statement.clone()),
|
||||||
|
verb: entry.kind.0.clone(),
|
||||||
|
render_path: state
|
||||||
|
.grammar
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|grammar| grammar.verb(&entry.kind.0))
|
||||||
|
.map(|verb| verb.render_path),
|
||||||
|
roles,
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.collect()
|
.collect()
|
||||||
|
|
@ -3962,6 +4321,7 @@ fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> {
|
||||||
id: *subject_id,
|
id: *subject_id,
|
||||||
label: subject.label.clone(),
|
label: subject.label.clone(),
|
||||||
kind: subject.kind,
|
kind: subject.kind,
|
||||||
|
import_key: subject.import_key.clone(),
|
||||||
controller_id: controller.id(),
|
controller_id: controller.id(),
|
||||||
controller_mode: controller.mode(),
|
controller_mode: controller.mode(),
|
||||||
human_controller: controller.human_principal().cloned(),
|
human_controller: controller.human_principal().cloned(),
|
||||||
|
|
@ -3998,6 +4358,17 @@ fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> {
|
||||||
magnitude: *magnitude,
|
magnitude: *magnitude,
|
||||||
})
|
})
|
||||||
.collect(),
|
.collect(),
|
||||||
|
opinions: attitude::opinions_held(state, *subject_id)
|
||||||
|
.into_iter()
|
||||||
|
.map(|(toward, mut held)| {
|
||||||
|
held.causes.truncate(attitude::OPINION_CAUSES_SHOWN);
|
||||||
|
OpinionSnapshot {
|
||||||
|
toward,
|
||||||
|
total: held.total,
|
||||||
|
causes: held.causes,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
qualified: qualifies(state, *subject_id),
|
qualified: qualifies(state, *subject_id),
|
||||||
last_acted_at: last_acted_at.get(subject_id).copied(),
|
last_acted_at: last_acted_at.get(subject_id).copied(),
|
||||||
})
|
})
|
||||||
|
|
@ -4077,6 +4448,8 @@ 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),
|
||||||
draft_approvals: state.draft_approvals.clone(),
|
draft_approvals: state.draft_approvals.clone(),
|
||||||
required_approvers: required_approvers(state),
|
required_approvers: required_approvers(state),
|
||||||
subjects,
|
subjects,
|
||||||
|
|
@ -4086,6 +4459,11 @@ fn snapshot(state: &WorldState) -> Result<WorldSnapshot, KernelError> {
|
||||||
.map(|(affordance_id, entry)| AffordanceSnapshot {
|
.map(|(affordance_id, entry)| AffordanceSnapshot {
|
||||||
id: *affordance_id,
|
id: *affordance_id,
|
||||||
entry: entry.clone(),
|
entry: entry.clone(),
|
||||||
|
render_path: state
|
||||||
|
.grammar
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|grammar| grammar.verb(&entry.kind.0))
|
||||||
|
.map(|verb| verb.render_path),
|
||||||
})
|
})
|
||||||
.collect(),
|
.collect(),
|
||||||
places,
|
places,
|
||||||
|
|
@ -5094,6 +5472,16 @@ fn operation_ground(
|
||||||
}
|
}
|
||||||
(subjects, places(named), routes)
|
(subjects, places(named), routes)
|
||||||
}
|
}
|
||||||
|
// An attitude is the holder's own state about another subject, so both
|
||||||
|
// are ground; a trait names none.
|
||||||
|
ResolvedOp::AdjustAttitude { holder, key, .. } => {
|
||||||
|
let mut subjects = vec![*holder];
|
||||||
|
if let AttitudeToward::Subject(target) = &key.toward {
|
||||||
|
subjects.push(*target);
|
||||||
|
}
|
||||||
|
(subjects, Vec::new(), Vec::new())
|
||||||
|
}
|
||||||
|
ResolvedOp::DeclareTrait { subject, .. } => (vec![*subject], Vec::new(), Vec::new()),
|
||||||
// Confinement never reaches these through the ordinary ground check:
|
// Confinement never reaches these through the ordinary ground check:
|
||||||
// `confine_to_ground` refuses `Retire`, `GrantAffordance`, and
|
// `confine_to_ground` refuses `Retire`, `GrantAffordance`, and
|
||||||
// `RevokeAffordance` unconditionally for every confined author before
|
// `RevokeAffordance` unconditionally for every confined author before
|
||||||
|
|
@ -5436,6 +5824,7 @@ mod tests {
|
||||||
// The fixture world is one room. Co-located speech needs a place to
|
// The fixture world is one room. Co-located speech needs a place to
|
||||||
// fill, so every fixture subject stands in the commons.
|
// fill, so every fixture subject stands in the commons.
|
||||||
position: Some(Ref::Draft(DraftHandle::new(COMMONS))),
|
position: Some(Ref::Draft(DraftHandle::new(COMMONS))),
|
||||||
|
import_key: None,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -5538,11 +5927,14 @@ mod tests {
|
||||||
.chain(std::iter::once(Ref::Draft(DraftHandle::new("convene"))))
|
.chain(std::iter::once(Ref::Draft(DraftHandle::new("convene"))))
|
||||||
.collect(),
|
.collect(),
|
||||||
position: Some(Ref::Draft(DraftHandle::new(COMMONS))),
|
position: Some(Ref::Draft(DraftHandle::new(COMMONS))),
|
||||||
|
import_key: None,
|
||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
scale_intent: WorldScaleIntentRef::default(),
|
scale_intent: WorldScaleIntentRef::default(),
|
||||||
lens_weights: stock_weights(),
|
lens_weights: stock_weights(),
|
||||||
|
grammar: None,
|
||||||
|
era: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -5687,6 +6079,7 @@ mod tests {
|
||||||
controller: NewController::OperationalAgent,
|
controller: NewController::OperationalAgent,
|
||||||
affordances: BTreeSet::from([speak]),
|
affordances: BTreeSet::from([speak]),
|
||||||
position: Some(Ref::Draft(DraftHandle::new("yard"))),
|
position: Some(Ref::Draft(DraftHandle::new("yard"))),
|
||||||
|
import_key: None,
|
||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
// A route that should start closed is declared and closed in one
|
// A route that should start closed is declared and closed in one
|
||||||
|
|
@ -5792,6 +6185,7 @@ mod tests {
|
||||||
}))
|
}))
|
||||||
.collect(),
|
.collect(),
|
||||||
position: Some(Ref::Existing(place)),
|
position: Some(Ref::Existing(place)),
|
||||||
|
import_key: None,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -6312,6 +6706,7 @@ mod tests {
|
||||||
controller: NewController::OperationalAgent,
|
controller: NewController::OperationalAgent,
|
||||||
affordances: civic_grants(handles, &speak),
|
affordances: civic_grants(handles, &speak),
|
||||||
position: Some(place),
|
position: Some(place),
|
||||||
|
import_key: None,
|
||||||
})
|
})
|
||||||
};
|
};
|
||||||
let declarations = civic_affordances()
|
let declarations = civic_affordances()
|
||||||
|
|
@ -6368,6 +6763,7 @@ mod tests {
|
||||||
&speak,
|
&speak,
|
||||||
),
|
),
|
||||||
position: Some(Ref::Draft(DraftHandle::new("hall"))),
|
position: Some(Ref::Draft(DraftHandle::new("hall"))),
|
||||||
|
import_key: None,
|
||||||
}),
|
}),
|
||||||
Declaration::Subject(SubjectDeclaration {
|
Declaration::Subject(SubjectDeclaration {
|
||||||
handle: DraftHandle::new("reeve"),
|
handle: DraftHandle::new("reeve"),
|
||||||
|
|
@ -6379,6 +6775,7 @@ mod tests {
|
||||||
&speak,
|
&speak,
|
||||||
),
|
),
|
||||||
position: Some(Ref::Draft(DraftHandle::new("chamber"))),
|
position: Some(Ref::Draft(DraftHandle::new("chamber"))),
|
||||||
|
import_key: None,
|
||||||
}),
|
}),
|
||||||
person(
|
person(
|
||||||
"farmer",
|
"farmer",
|
||||||
|
|
@ -6402,6 +6799,7 @@ mod tests {
|
||||||
controller: NewController::NarrativePersona,
|
controller: NewController::NarrativePersona,
|
||||||
affordances: civic_grants(&["levy", "petition"], &speak),
|
affordances: civic_grants(&["levy", "petition"], &speak),
|
||||||
position: None,
|
position: None,
|
||||||
|
import_key: None,
|
||||||
}),
|
}),
|
||||||
])
|
])
|
||||||
.collect();
|
.collect();
|
||||||
|
|
@ -6565,6 +6963,7 @@ mod tests {
|
||||||
Ref::Draft(DraftHandle::new("recant")),
|
Ref::Draft(DraftHandle::new("recant")),
|
||||||
]),
|
]),
|
||||||
position: place.map(|place| Ref::Draft(DraftHandle::new(place))),
|
position: place.map(|place| Ref::Draft(DraftHandle::new(place))),
|
||||||
|
import_key: None,
|
||||||
})
|
})
|
||||||
};
|
};
|
||||||
submit_owner(
|
submit_owner(
|
||||||
|
|
@ -7833,6 +8232,7 @@ mod tests {
|
||||||
controller: NewController::OperationalAgent,
|
controller: NewController::OperationalAgent,
|
||||||
affordances: BTreeSet::from([speak.clone()]),
|
affordances: BTreeSet::from([speak.clone()]),
|
||||||
position: Some(Ref::Existing(topology.road)),
|
position: Some(Ref::Existing(topology.road)),
|
||||||
|
import_key: None,
|
||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
operations: Vec::new(),
|
operations: Vec::new(),
|
||||||
|
|
@ -8851,6 +9251,7 @@ mod custody_tests {
|
||||||
controller: NewController::OperationalAgent,
|
controller: NewController::OperationalAgent,
|
||||||
affordances: BTreeSet::from([speak.clone()]),
|
affordances: BTreeSet::from([speak.clone()]),
|
||||||
position: Some(Ref::Existing(topology.yard)),
|
position: Some(Ref::Existing(topology.yard)),
|
||||||
|
import_key: None,
|
||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
operations: vec![ComponentOp::Admit {
|
operations: vec![ComponentOp::Admit {
|
||||||
|
|
@ -9510,6 +9911,7 @@ mod custody_tests {
|
||||||
controller: NewController::OperationalAgent,
|
controller: NewController::OperationalAgent,
|
||||||
affordances: BTreeSet::from([speak.clone()]),
|
affordances: BTreeSet::from([speak.clone()]),
|
||||||
position: Some(Ref::Existing(topology.yard)),
|
position: Some(Ref::Existing(topology.yard)),
|
||||||
|
import_key: None,
|
||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
operations: vec![admit(u64::MAX), admit(1)],
|
operations: vec![admit(u64::MAX), admit(1)],
|
||||||
|
|
@ -11436,7 +11838,7 @@ mod soul_knowledge_tests {
|
||||||
// Nobody holds it.
|
// Nobody holds it.
|
||||||
assert!(kernel.state.knowledge.is_empty());
|
assert!(kernel.state.knowledge.is_empty());
|
||||||
// The operator reads it anyway, with the speaker resolved by label.
|
// The operator reads it anyway, with the speaker resolved by label.
|
||||||
let log = operator_log(&kernel.state).unwrap();
|
let log = kernel.operator_log().unwrap();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
log,
|
log,
|
||||||
vec![OperatorEvent {
|
vec![OperatorEvent {
|
||||||
|
|
@ -11445,6 +11847,9 @@ mod soul_knowledge_tests {
|
||||||
speaker_label: "The Yard Bystander".into(),
|
speaker_label: "The Yard Bystander".into(),
|
||||||
speech: Some(Statement::new(text).unwrap()),
|
speech: Some(Statement::new(text).unwrap()),
|
||||||
display: None,
|
display: None,
|
||||||
|
verb: "speak".into(),
|
||||||
|
render_path: None,
|
||||||
|
roles: Vec::new(),
|
||||||
}]
|
}]
|
||||||
);
|
);
|
||||||
// And no subject snapshot carries it.
|
// And no subject snapshot carries it.
|
||||||
|
|
@ -11502,6 +11907,7 @@ mod witness_tests {
|
||||||
controller: NewController::NarrativePersona,
|
controller: NewController::NarrativePersona,
|
||||||
affordances: BTreeSet::from([speak.clone(), Ref::Draft(DraftHandle::new("beacon"))]),
|
affordances: BTreeSet::from([speak.clone(), Ref::Draft(DraftHandle::new("beacon"))]),
|
||||||
position: Some(Ref::Draft(DraftHandle::new(place))),
|
position: Some(Ref::Draft(DraftHandle::new(place))),
|
||||||
|
import_key: None,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -12615,6 +13021,7 @@ mod witness_tests {
|
||||||
// Every non-mirror subject must hold one.
|
// Every non-mirror subject must hold one.
|
||||||
affordances: BTreeSet::from([Ref::Existing(beacon)]),
|
affordances: BTreeSet::from([Ref::Existing(beacon)]),
|
||||||
position: position.map(Ref::Existing),
|
position: position.map(Ref::Existing),
|
||||||
|
import_key: None,
|
||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
operations: vec![witness(
|
operations: vec![witness(
|
||||||
|
|
@ -12928,6 +13335,8 @@ mod clock_tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
|
mod attitude_tests;
|
||||||
|
|
||||||
/// The canonical IDs of the clock fixture: a hall containing a yard, a
|
/// The canonical IDs of the clock fixture: a hall containing a yard, a
|
||||||
/// dead end reached by exactly one route, three subjects, a resource, and
|
/// dead end reached by exactly one route, three subjects, a resource, and
|
||||||
/// one commitment of each kind.
|
/// one commitment of each kind.
|
||||||
|
|
@ -12979,6 +13388,7 @@ mod clock_tests {
|
||||||
Ref::Draft(DraftHandle::new("threaten")),
|
Ref::Draft(DraftHandle::new("threaten")),
|
||||||
]),
|
]),
|
||||||
position: Some(Ref::Draft(DraftHandle::new(place))),
|
position: Some(Ref::Draft(DraftHandle::new(place))),
|
||||||
|
import_key: None,
|
||||||
})
|
})
|
||||||
};
|
};
|
||||||
let subject = |handle: &str| Ref::Draft(DraftHandle::new(handle));
|
let subject = |handle: &str| Ref::Draft(DraftHandle::new(handle));
|
||||||
|
|
@ -15055,6 +15465,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();
|
||||||
|
|
@ -15160,7 +15617,7 @@ mod clock_tests {
|
||||||
}));
|
}));
|
||||||
let title = normalize_title(&input.title).unwrap();
|
let title = normalize_title(&input.title).unwrap();
|
||||||
let resolved = patch::resolve_patch(
|
let resolved = patch::resolve_patch(
|
||||||
&WorldState::empty(world_id, input.owner.clone(), title.clone()),
|
&WorldState::empty(world_id, input.owner.clone(), title.clone(), None),
|
||||||
input.id,
|
input.id,
|
||||||
&input.patch,
|
&input.patch,
|
||||||
Some(&input.scale_intent),
|
Some(&input.scale_intent),
|
||||||
|
|
@ -15189,7 +15646,7 @@ mod clock_tests {
|
||||||
});
|
});
|
||||||
let title = normalize_title(&input.title).unwrap();
|
let title = normalize_title(&input.title).unwrap();
|
||||||
let resolved = patch::resolve_patch(
|
let resolved = patch::resolve_patch(
|
||||||
&WorldState::empty(world_id, input.owner.clone(), title.clone()),
|
&WorldState::empty(world_id, input.owner.clone(), title.clone(), None),
|
||||||
input.id,
|
input.id,
|
||||||
&input.patch,
|
&input.patch,
|
||||||
Some(&input.scale_intent),
|
Some(&input.scale_intent),
|
||||||
|
|
@ -17032,6 +17489,7 @@ mod clock_tests {
|
||||||
controller: NewController::NarrativePersona,
|
controller: NewController::NarrativePersona,
|
||||||
affordances: BTreeSet::from([speak]),
|
affordances: BTreeSet::from([speak]),
|
||||||
position: Some(Ref::Existing(clockwork.dead_end)),
|
position: Some(Ref::Existing(clockwork.dead_end)),
|
||||||
|
import_key: None,
|
||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
operations: Vec::new(),
|
operations: Vec::new(),
|
||||||
|
|
@ -17098,6 +17556,7 @@ mod clock_tests {
|
||||||
controller: NewController::NarrativePersona,
|
controller: NewController::NarrativePersona,
|
||||||
affordances: BTreeSet::from([speak]),
|
affordances: BTreeSet::from([speak]),
|
||||||
position: Some(Ref::Existing(clockwork.dead_end)),
|
position: Some(Ref::Existing(clockwork.dead_end)),
|
||||||
|
import_key: None,
|
||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
operations: Vec::new(),
|
operations: Vec::new(),
|
||||||
|
|
@ -17175,6 +17634,7 @@ mod clock_tests {
|
||||||
},
|
},
|
||||||
affordances: BTreeSet::new(),
|
affordances: BTreeSet::new(),
|
||||||
position: Some(Ref::Existing(commons)),
|
position: Some(Ref::Existing(commons)),
|
||||||
|
import_key: None,
|
||||||
})],
|
})],
|
||||||
operations: Vec::new(),
|
operations: Vec::new(),
|
||||||
evidence: Vec::new(),
|
evidence: Vec::new(),
|
||||||
|
|
@ -17268,6 +17728,7 @@ mod clock_tests {
|
||||||
controller: NewController::NarrativePersona,
|
controller: NewController::NarrativePersona,
|
||||||
affordances: BTreeSet::from([speak]),
|
affordances: BTreeSet::from([speak]),
|
||||||
position: Some(Ref::Existing(clockwork.dead_end)),
|
position: Some(Ref::Existing(clockwork.dead_end)),
|
||||||
|
import_key: None,
|
||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
operations: vec![ComponentOp::Mint {
|
operations: vec![ComponentOp::Mint {
|
||||||
|
|
@ -17510,6 +17971,7 @@ mod clock_tests {
|
||||||
// the boundary its own answer claims: an occupied
|
// the boundary its own answer claims: an occupied
|
||||||
// place is no longer unelaborated.
|
// place is no longer unelaborated.
|
||||||
position: Some(Ref::Existing(clockwork.dead_end)),
|
position: Some(Ref::Existing(clockwork.dead_end)),
|
||||||
|
import_key: None,
|
||||||
})],
|
})],
|
||||||
operations: Vec::new(),
|
operations: Vec::new(),
|
||||||
evidence: Vec::new(),
|
evidence: Vec::new(),
|
||||||
|
|
@ -17688,6 +18150,7 @@ mod clock_tests {
|
||||||
controller: NewController::NarrativePersona,
|
controller: NewController::NarrativePersona,
|
||||||
affordances: BTreeSet::from([speak]),
|
affordances: BTreeSet::from([speak]),
|
||||||
position: Some(Ref::Existing(clockwork.dead_end)),
|
position: Some(Ref::Existing(clockwork.dead_end)),
|
||||||
|
import_key: None,
|
||||||
})],
|
})],
|
||||||
operations: vec![ComponentOp::Retire {
|
operations: vec![ComponentOp::Retire {
|
||||||
subject: Ref::Draft(DraftHandle::new("stray")),
|
subject: Ref::Draft(DraftHandle::new("stray")),
|
||||||
|
|
@ -17797,6 +18260,7 @@ mod clock_tests {
|
||||||
controller: NewController::NarrativePersona,
|
controller: NewController::NarrativePersona,
|
||||||
affordances: BTreeSet::from([speak]),
|
affordances: BTreeSet::from([speak]),
|
||||||
position: Some(Ref::Existing(commons)),
|
position: Some(Ref::Existing(commons)),
|
||||||
|
import_key: None,
|
||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
operations: vec![ComponentOp::GrantAffordance {
|
operations: vec![ComponentOp::GrantAffordance {
|
||||||
|
|
@ -18011,6 +18475,7 @@ mod clock_tests {
|
||||||
controller: NewController::NarrativePersona,
|
controller: NewController::NarrativePersona,
|
||||||
affordances: BTreeSet::from([speak]),
|
affordances: BTreeSet::from([speak]),
|
||||||
position: Some(Ref::Existing(clockwork.dead_end)),
|
position: Some(Ref::Existing(clockwork.dead_end)),
|
||||||
|
import_key: None,
|
||||||
})],
|
})],
|
||||||
operations: vec![ComponentOp::GrantAffordance {
|
operations: vec![ComponentOp::GrantAffordance {
|
||||||
subject: Ref::Draft(DraftHandle::new("stray")),
|
subject: Ref::Draft(DraftHandle::new("stray")),
|
||||||
|
|
@ -18429,6 +18894,7 @@ mod clock_tests {
|
||||||
Ref::Existing(clockwork.threaten),
|
Ref::Existing(clockwork.threaten),
|
||||||
]),
|
]),
|
||||||
position: Some(Ref::Existing(clockwork.dead_end)),
|
position: Some(Ref::Existing(clockwork.dead_end)),
|
||||||
|
import_key: None,
|
||||||
})],
|
})],
|
||||||
operations: vec![ComponentOp::RevokeAffordance {
|
operations: vec![ComponentOp::RevokeAffordance {
|
||||||
subject: Ref::Draft(DraftHandle::new("stray")),
|
subject: Ref::Draft(DraftHandle::new("stray")),
|
||||||
|
|
@ -18877,6 +19343,7 @@ mod clock_tests {
|
||||||
controller: NewController::NarrativePersona,
|
controller: NewController::NarrativePersona,
|
||||||
affordances: BTreeSet::from([speak.clone()]),
|
affordances: BTreeSet::from([speak.clone()]),
|
||||||
position: None,
|
position: None,
|
||||||
|
import_key: None,
|
||||||
}),
|
}),
|
||||||
Declaration::Channel(ChannelDeclaration {
|
Declaration::Channel(ChannelDeclaration {
|
||||||
handle: DraftHandle::new("wire"),
|
handle: DraftHandle::new("wire"),
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,13 +1,15 @@
|
||||||
use super::{
|
use super::{
|
||||||
AgencyGraph, AuthenticatedCaller, CallerId, CommandBody, CommandEnvelope, CommandId,
|
AgencyGraph, AuthenticatedCaller, Hierarchy, CallerId, CommandBody, CommandEnvelope, CommandId,
|
||||||
ConsumerId, CreateWorld, CreateWorldIntent, CreationReceipt, DecisionInvocation,
|
ConsumerId, CreateWorld, CreateWorldIntent, CreationReceipt, DecisionInvocation,
|
||||||
DecisionOpportunity, Declaration, DraftHandle, EntityDeclaration, EntityKind, JurisdictionKey,
|
DecisionOpportunity, Declaration, DraftHandle, EntityDeclaration, EntityKind, JurisdictionKey,
|
||||||
KernelError, NewController, OperatorEvent, PatchAnswer, PrincipalCommandIntent, PrincipalId,
|
KernelError, NewController, OperatorEvent, PatchAnswer, PrincipalCommandIntent, PrincipalId,
|
||||||
Ref, SubjectDeclaration, SubjectKind, SubmitReceipt, SystemCapability, TickMinutes, WorldId,
|
EntityId, Ref, SubjectDeclaration, SubjectKind, SubmitReceipt, SystemCapability, TickMinutes, WorldId,
|
||||||
WorldKernel, WorldPatch, WorldPhase, WorldScaleIntentRef, WorldSnapshot, journal,
|
WorldKernel, WorldPatch, WorldPhase, WorldScaleIntentRef, WorldSnapshot, journal,
|
||||||
patch::kernel_speak_grant, prepare_creation,
|
patch::kernel_speak_grant, prepare_creation,
|
||||||
|
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;
|
||||||
|
|
@ -18,6 +20,21 @@ use tokio::task::JoinHandle;
|
||||||
/// other. A world that wants more declares them through the patch lane.
|
/// other. A world that wants more declares them through the patch lane.
|
||||||
const GENESIS_PLACE: &str = "commons";
|
const GENESIS_PLACE: &str = "commons";
|
||||||
|
|
||||||
|
/// The commons every genesis declares, the one room its first subjects share.
|
||||||
|
pub(crate) fn commons_declaration() -> Declaration {
|
||||||
|
Declaration::Entity(EntityDeclaration {
|
||||||
|
handle: DraftHandle::new(GENESIS_PLACE),
|
||||||
|
label: "The Commons".into(),
|
||||||
|
kind: EntityKind::Place,
|
||||||
|
container: None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where a genesis subject stands.
|
||||||
|
pub(crate) fn commons_ref() -> Ref<EntityId> {
|
||||||
|
Ref::Draft(DraftHandle::new(GENESIS_PLACE))
|
||||||
|
}
|
||||||
|
|
||||||
const REQUEST_CAPACITY: usize = 32;
|
const REQUEST_CAPACITY: usize = 32;
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
|
|
@ -66,6 +83,21 @@ enum Request {
|
||||||
AgencyGraph {
|
AgencyGraph {
|
||||||
reply: oneshot::Sender<Result<AgencyGraph, KernelError>>,
|
reply: oneshot::Sender<Result<AgencyGraph, KernelError>>,
|
||||||
},
|
},
|
||||||
|
/// The gestalt hierarchy, derived from world state. Separate from
|
||||||
|
/// `Snapshot` as `AgencyGraph` is: only the tick driver may hold it.
|
||||||
|
Hierarchy {
|
||||||
|
reply: oneshot::Sender<Result<Hierarchy, KernelError>>,
|
||||||
|
},
|
||||||
|
/// The tick driver's opportunity list. Separate from `Snapshot` so the
|
||||||
|
/// list a cover is derived from has one door, held by the driver.
|
||||||
|
Opportunities {
|
||||||
|
reply: oneshot::Sender<Result<Vec<DecisionOpportunity>, KernelError>>,
|
||||||
|
},
|
||||||
|
/// The tick ordinal's one door: how many clock advances the world has
|
||||||
|
/// committed. Held by the tick driver, as `Opportunities` is.
|
||||||
|
ClockAdvances {
|
||||||
|
reply: oneshot::Sender<Result<u64, KernelError>>,
|
||||||
|
},
|
||||||
ControllerReceipt {
|
ControllerReceipt {
|
||||||
command_id: CommandId,
|
command_id: CommandId,
|
||||||
opportunity: super::DecisionOpportunity,
|
opportunity: super::DecisionOpportunity,
|
||||||
|
|
@ -120,7 +152,8 @@ impl WorldMailbox {
|
||||||
kind,
|
kind,
|
||||||
controller,
|
controller,
|
||||||
affordances: kernel_speak_grant(),
|
affordances: kernel_speak_grant(),
|
||||||
position: Some(Ref::Draft(DraftHandle::new(GENESIS_PLACE))),
|
position: Some(commons_ref()),
|
||||||
|
import_key: None,
|
||||||
})
|
})
|
||||||
};
|
};
|
||||||
// Roots stand beside the commons, not inside it: a root contained by
|
// Roots stand beside the commons, not inside it: a root contained by
|
||||||
|
|
@ -129,12 +162,7 @@ impl WorldMailbox {
|
||||||
// jurisdiction's population target. The owner subject lands in
|
// jurisdiction's population target. The owner subject lands in
|
||||||
// `Uncovered`, visible and reducing nothing.
|
// `Uncovered`, visible and reducing nothing.
|
||||||
let mut declarations = vec![
|
let mut declarations = vec![
|
||||||
Declaration::Entity(EntityDeclaration {
|
commons_declaration(),
|
||||||
handle: DraftHandle::new(GENESIS_PLACE),
|
|
||||||
label: "The Commons".into(),
|
|
||||||
kind: EntityKind::Place,
|
|
||||||
container: None,
|
|
||||||
}),
|
|
||||||
declare(
|
declare(
|
||||||
"first-person",
|
"first-person",
|
||||||
input.human_subject_label,
|
input.human_subject_label,
|
||||||
|
|
@ -189,6 +217,8 @@ impl WorldMailbox {
|
||||||
},
|
},
|
||||||
scale_intent,
|
scale_intent,
|
||||||
lens_weights: input.lens_weights,
|
lens_weights: input.lens_weights,
|
||||||
|
grammar: None,
|
||||||
|
era: input.era,
|
||||||
},
|
},
|
||||||
AuthenticatedCaller::verified_principal(principal_id),
|
AuthenticatedCaller::verified_principal(principal_id),
|
||||||
)
|
)
|
||||||
|
|
@ -217,6 +247,20 @@ impl WorldMailbox {
|
||||||
.map_err(mailbox_outcome)
|
.map_err(mailbox_outcome)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Creates the canonical Aetheria verse world through the same
|
||||||
|
/// authenticated creation `create` uses.
|
||||||
|
pub async fn create_verse(
|
||||||
|
&self,
|
||||||
|
intent: CreateVerseWorldIntent,
|
||||||
|
principal: &VerifiedPrincipalEvidence,
|
||||||
|
) -> Result<CreationReceipt, VerseGenesisError> {
|
||||||
|
let principal_id = PrincipalId::new(principal.account_subject_hash());
|
||||||
|
let input = intent.lower(principal_id.clone())?;
|
||||||
|
Ok(self
|
||||||
|
.create_authenticated(input, AuthenticatedCaller::verified_principal(principal_id))
|
||||||
|
.await?)
|
||||||
|
}
|
||||||
|
|
||||||
/// A wall-clock read at the boundary a request crosses into the mailbox is
|
/// A wall-clock read at the boundary a request crosses into the mailbox is
|
||||||
/// ingress, not reduce: the reducer stays deterministic over its journal,
|
/// ingress, not reduce: the reducer stays deterministic over its journal,
|
||||||
/// and this is the one place a caller's own claim of continued authority
|
/// and this is the one place a caller's own claim of continued authority
|
||||||
|
|
@ -459,6 +503,54 @@ impl WorldMailbox {
|
||||||
.map_err(MailboxError::Kernel)
|
.map_err(MailboxError::Kernel)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The tick driver's projection of the gestalt hierarchy, derived afresh
|
||||||
|
/// from the world on every call. It is on `WorldMailbox` and on neither
|
||||||
|
/// `ControllerPort` nor `ElaborationPort`, as `agency_graph` is: the tree
|
||||||
|
/// is wider than any subject view.
|
||||||
|
pub async fn hierarchy(&self) -> Result<Hierarchy, MailboxError> {
|
||||||
|
let (reply, response) = oneshot::channel();
|
||||||
|
self.sender
|
||||||
|
.send(Request::Hierarchy { reply })
|
||||||
|
.await
|
||||||
|
.map_err(|_| MailboxError::Unavailable)?;
|
||||||
|
|
||||||
|
response
|
||||||
|
.await
|
||||||
|
.map_err(|_| MailboxError::Unavailable)?
|
||||||
|
.map_err(MailboxError::Kernel)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The tick driver's opportunity list, in snapshot order. It is on
|
||||||
|
/// `WorldMailbox` and on no controller port, as `agency_graph` is.
|
||||||
|
pub async fn opportunities(&self) -> Result<Vec<DecisionOpportunity>, MailboxError> {
|
||||||
|
let (reply, response) = oneshot::channel();
|
||||||
|
self.sender
|
||||||
|
.send(Request::Opportunities { reply })
|
||||||
|
.await
|
||||||
|
.map_err(|_| MailboxError::Unavailable)?;
|
||||||
|
|
||||||
|
response
|
||||||
|
.await
|
||||||
|
.map_err(|_| MailboxError::Unavailable)?
|
||||||
|
.map_err(MailboxError::Kernel)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The tick driver's ordinal: how many clock advances the world has
|
||||||
|
/// committed. It is on `WorldMailbox` and on no controller port, as
|
||||||
|
/// `opportunities` is.
|
||||||
|
pub async fn clock_advances(&self) -> Result<u64, MailboxError> {
|
||||||
|
let (reply, response) = oneshot::channel();
|
||||||
|
self.sender
|
||||||
|
.send(Request::ClockAdvances { reply })
|
||||||
|
.await
|
||||||
|
.map_err(|_| MailboxError::Unavailable)?;
|
||||||
|
|
||||||
|
response
|
||||||
|
.await
|
||||||
|
.map_err(|_| MailboxError::Unavailable)?
|
||||||
|
.map_err(MailboxError::Kernel)
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn operator_log(&self) -> Result<Vec<OperatorEvent>, MailboxError> {
|
pub async fn operator_log(&self) -> Result<Vec<OperatorEvent>, MailboxError> {
|
||||||
let (reply, response) = oneshot::channel();
|
let (reply, response) = oneshot::channel();
|
||||||
self.sender
|
self.sender
|
||||||
|
|
@ -648,6 +740,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.
|
||||||
|
|
@ -928,6 +1112,45 @@ async fn run_owner(mut owned: OwnedWorld, mut receiver: mpsc::Receiver<Request>)
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Request::Hierarchy { reply } => {
|
||||||
|
let result = match &owned {
|
||||||
|
OwnedWorld::Empty(_) => Err(KernelError::WorldNotCreated),
|
||||||
|
OwnedWorld::Live(kernel) => kernel.hierarchy(),
|
||||||
|
};
|
||||||
|
let owner_must_stop = result
|
||||||
|
.as_ref()
|
||||||
|
.is_err_and(KernelError::requires_owner_restart);
|
||||||
|
let _ = reply.send(result);
|
||||||
|
if owner_must_stop {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Request::Opportunities { reply } => {
|
||||||
|
let result = match &owned {
|
||||||
|
OwnedWorld::Empty(_) => Err(KernelError::WorldNotCreated),
|
||||||
|
OwnedWorld::Live(kernel) => kernel.opportunities(),
|
||||||
|
};
|
||||||
|
let owner_must_stop = result
|
||||||
|
.as_ref()
|
||||||
|
.is_err_and(KernelError::requires_owner_restart);
|
||||||
|
let _ = reply.send(result);
|
||||||
|
if owner_must_stop {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Request::ClockAdvances { reply } => {
|
||||||
|
let result = match &owned {
|
||||||
|
OwnedWorld::Empty(_) => Err(KernelError::WorldNotCreated),
|
||||||
|
OwnedWorld::Live(kernel) => kernel.clock_advances(),
|
||||||
|
};
|
||||||
|
let owner_must_stop = result
|
||||||
|
.as_ref()
|
||||||
|
.is_err_and(KernelError::requires_owner_restart);
|
||||||
|
let _ = reply.send(result);
|
||||||
|
if owner_must_stop {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
Request::ControllerReceipt {
|
Request::ControllerReceipt {
|
||||||
command_id,
|
command_id,
|
||||||
opportunity,
|
opportunity,
|
||||||
|
|
@ -988,6 +1211,8 @@ mod tests {
|
||||||
fn creation(id: CommandId, title: &str) -> CreateWorld {
|
fn creation(id: CommandId, title: &str) -> CreateWorld {
|
||||||
CreateWorld {
|
CreateWorld {
|
||||||
lens_weights: crate::tests::stock_weights(),
|
lens_weights: crate::tests::stock_weights(),
|
||||||
|
grammar: None,
|
||||||
|
era: None,
|
||||||
id,
|
id,
|
||||||
owner: PrincipalId::new("owner"),
|
owner: PrincipalId::new("owner"),
|
||||||
title: title.into(),
|
title: title.into(),
|
||||||
|
|
@ -1009,6 +1234,7 @@ mod tests {
|
||||||
},
|
},
|
||||||
affordances: kernel_speak_grant(),
|
affordances: kernel_speak_grant(),
|
||||||
position: Some(Ref::Draft(DraftHandle::new(GENESIS_PLACE))),
|
position: Some(Ref::Draft(DraftHandle::new(GENESIS_PLACE))),
|
||||||
|
import_key: None,
|
||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
operations: Vec::new(),
|
operations: Vec::new(),
|
||||||
|
|
@ -1057,6 +1283,22 @@ mod tests {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn hierarchy_is_derived_from_the_world_through_the_mailbox() {
|
||||||
|
let (_directory, _path, mailbox, task, _authenticated, _input, _receipt) = fixture().await;
|
||||||
|
let hierarchy = mailbox.hierarchy().await.unwrap();
|
||||||
|
let snapshot = mailbox.snapshot().await.unwrap();
|
||||||
|
// The fixture world holds one Human operator in one room: placed under
|
||||||
|
// that room's node, no voice anywhere.
|
||||||
|
assert_eq!(hierarchy.home.len(), 1);
|
||||||
|
assert!(hierarchy.nodes.values().all(|node| node.voice.is_none() && node.loose.is_empty()));
|
||||||
|
assert_eq!(hierarchy.nodes.len(), 2);
|
||||||
|
assert_eq!(hierarchy, mailbox.hierarchy().await.unwrap());
|
||||||
|
assert_eq!(snapshot.subjects.len(), 1);
|
||||||
|
drop(mailbox);
|
||||||
|
task.await.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn empty_owner_rejects_world_operations_then_accepts_creation() {
|
async fn empty_owner_rejects_world_operations_then_accepts_creation() {
|
||||||
let directory = tempfile::tempdir().unwrap();
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
|
@ -1396,6 +1638,7 @@ mod tests {
|
||||||
controller,
|
controller,
|
||||||
affordances: kernel_speak_grant(),
|
affordances: kernel_speak_grant(),
|
||||||
position: Some(Ref::Draft(DraftHandle::new(format!("room-{handle}")))),
|
position: Some(Ref::Draft(DraftHandle::new(format!("room-{handle}")))),
|
||||||
|
import_key: None,
|
||||||
})
|
})
|
||||||
};
|
};
|
||||||
let room = |handle: &str| {
|
let room = |handle: &str| {
|
||||||
|
|
@ -1425,6 +1668,8 @@ mod tests {
|
||||||
evidence: Vec::new(),
|
evidence: Vec::new(),
|
||||||
},
|
},
|
||||||
scale_intent: WorldScaleIntentRef::default(),
|
scale_intent: WorldScaleIntentRef::default(),
|
||||||
|
grammar: None,
|
||||||
|
era: None,
|
||||||
},
|
},
|
||||||
&authenticated,
|
&authenticated,
|
||||||
)
|
)
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load diff
296
crates/ghostlight/src/routed_inference.rs
Normal file
296
crates/ghostlight/src/routed_inference.rs
Normal file
|
|
@ -0,0 +1,296 @@
|
||||||
|
//! Prefix-based routing across the configured inference transports.
|
||||||
|
//!
|
||||||
|
//! `RoutedInferencePort` routes each model identifier to the longest matching
|
||||||
|
//! claimed prefix (`local/`, `hosted/`, etc.) and falls back to the connector
|
||||||
|
//! when no configured prefix claims the model.
|
||||||
|
|
||||||
|
use super::controllers::{
|
||||||
|
InferenceFault, InferenceOutput, InferencePort, InferenceRequest, PreparedInference,
|
||||||
|
};
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
/// Which port a lane uses is which model it is configured with. The config
|
||||||
|
/// already gates cognition by model name and deliberately refuses a mode flag,
|
||||||
|
/// so the transport is bound where the model is named and nowhere else.
|
||||||
|
pub(super) struct RoutedInferencePort {
|
||||||
|
connector: Option<Arc<dyn InferencePort>>,
|
||||||
|
/// The OpenAI-compatible ports (the loopback one and the hosted one), each
|
||||||
|
/// with its own claimed prefix carried beside it, so `route` can compare
|
||||||
|
/// lengths without a parallel field per port to keep in sync.
|
||||||
|
claims: Vec<(String, Arc<dyn InferencePort>)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RoutedInferencePort {
|
||||||
|
pub(super) fn new(
|
||||||
|
connector: Option<Arc<dyn InferencePort>>,
|
||||||
|
claims: Vec<(String, Arc<dyn InferencePort>)>,
|
||||||
|
) -> Self {
|
||||||
|
Self { connector, claims }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The model name carries the transport. When more than one prefix matches,
|
||||||
|
/// the longest claim wins. Any model no configured prefix claims falls to
|
||||||
|
/// the connector, or routes nowhere when no connector is bound.
|
||||||
|
pub(super) fn route(&self, model: &str) -> Option<&Arc<dyn InferencePort>> {
|
||||||
|
if let Some((_, port)) = self
|
||||||
|
.claims
|
||||||
|
.iter()
|
||||||
|
.filter(|(prefix, _)| model.starts_with(prefix.as_str()))
|
||||||
|
.max_by_key(|(prefix, _)| prefix.len())
|
||||||
|
{
|
||||||
|
return Some(port);
|
||||||
|
}
|
||||||
|
self.connector.as_ref()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl InferencePort for RoutedInferencePort {
|
||||||
|
fn prepare(&self, request: InferenceRequest) -> Result<PreparedInference, InferenceFault> {
|
||||||
|
let model = request.provider_model().to_owned();
|
||||||
|
match self.route(&model) {
|
||||||
|
Some(port) => port.prepare(request),
|
||||||
|
None => Err(InferenceFault::integrity_violation(
|
||||||
|
"no configured inference backend claims the requested model",
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn infer(&self, request: PreparedInference) -> Result<InferenceOutput, InferenceFault> {
|
||||||
|
let model = request.invocation.request.model.clone();
|
||||||
|
match self.route(&model) {
|
||||||
|
Some(port) => port.infer(request).await,
|
||||||
|
None => Err(InferenceFault::integrity_violation(
|
||||||
|
"no configured inference backend claims the requested model",
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::CommandId;
|
||||||
|
use crate::controllers::{
|
||||||
|
ConnectorBinding, ControllerModels, ControllerOpenError, InferencePurpose, RequestShape,
|
||||||
|
open_inference, tool_request, unix_ms,
|
||||||
|
};
|
||||||
|
use crate::local_inference::{
|
||||||
|
DEFAULT_HOSTED_MODEL_PREFIX, DEFAULT_LOCAL_MODEL_PREFIX, HostedBinding, LocalBinding,
|
||||||
|
};
|
||||||
|
use model_connector::{InputItem, ToolDefinition};
|
||||||
|
|
||||||
|
const TEST_RUNTIME: &str = "ghostlight-routed-test";
|
||||||
|
const TEST_MODEL: &str = "claude-opus-5-5";
|
||||||
|
|
||||||
|
struct StubPort;
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl InferencePort for StubPort {
|
||||||
|
fn prepare(&self, request: InferenceRequest) -> Result<PreparedInference, InferenceFault> {
|
||||||
|
PreparedInference::prepare(TEST_RUNTIME, unix_ms()?.saturating_add(60_000), request)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn infer(&self, _request: PreparedInference) -> Result<InferenceOutput, InferenceFault> {
|
||||||
|
Err(InferenceFault::integrity_violation("stub port"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn prose_request(prompt: &str) -> InferenceRequest {
|
||||||
|
tool_request(
|
||||||
|
CommandId::new(),
|
||||||
|
0,
|
||||||
|
InferencePurpose::Persona,
|
||||||
|
TEST_MODEL,
|
||||||
|
"Respond only in natural prose.",
|
||||||
|
vec![InputItem::UserText {
|
||||||
|
text: prompt.into(),
|
||||||
|
}],
|
||||||
|
Vec::<ToolDefinition>::new(),
|
||||||
|
RequestShape {
|
||||||
|
max_output_tokens: 1_200,
|
||||||
|
parallel_tool_calls: false,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.expect("the prose request builds")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn models(model: &str) -> ControllerModels {
|
||||||
|
ControllerModels {
|
||||||
|
projector: model.into(),
|
||||||
|
persona: model.into(),
|
||||||
|
interpreter: model.into(),
|
||||||
|
operational_agent: model.into(),
|
||||||
|
elaborator: model.into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn open_inference_routes_connector_local_hosted_only() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let connector_key = directory.path().join("connector.key");
|
||||||
|
let hosted_key = directory.path().join("hosted.key");
|
||||||
|
std::fs::write(&connector_key, "connector-test-key").unwrap();
|
||||||
|
std::fs::write(&hosted_key, "hosted-test-key").unwrap();
|
||||||
|
|
||||||
|
let connector = ConnectorBinding {
|
||||||
|
endpoint: "127.0.0.1:9".parse().unwrap(),
|
||||||
|
key_path: connector_key,
|
||||||
|
caller_runtime_id: TEST_RUNTIME.into(),
|
||||||
|
};
|
||||||
|
let local = LocalBinding {
|
||||||
|
endpoint: "127.0.0.1:9".parse().unwrap(),
|
||||||
|
model_prefix: DEFAULT_LOCAL_MODEL_PREFIX.into(),
|
||||||
|
caller_runtime_id: TEST_RUNTIME.into(),
|
||||||
|
};
|
||||||
|
let hosted = HostedBinding {
|
||||||
|
base_url: "https://api.example.test".into(),
|
||||||
|
key_path: hosted_key.clone(),
|
||||||
|
model_prefix: DEFAULT_HOSTED_MODEL_PREFIX.into(),
|
||||||
|
caller_runtime_id: TEST_RUNTIME.into(),
|
||||||
|
};
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
open_inference(
|
||||||
|
Some(connector),
|
||||||
|
Some(local),
|
||||||
|
Some(hosted),
|
||||||
|
&["claude-opus-5-5", "local/llama-8b", "hosted/deepseek-chat"],
|
||||||
|
)
|
||||||
|
.is_ok()
|
||||||
|
);
|
||||||
|
|
||||||
|
let connector_port = Arc::new(StubPort) as Arc<dyn InferencePort>;
|
||||||
|
let local_port = Arc::new(StubPort) as Arc<dyn InferencePort>;
|
||||||
|
let hosted_port = Arc::new(StubPort) as Arc<dyn InferencePort>;
|
||||||
|
let routed = RoutedInferencePort::new(
|
||||||
|
Some(Arc::clone(&connector_port)),
|
||||||
|
vec![
|
||||||
|
(DEFAULT_LOCAL_MODEL_PREFIX.to_owned(), Arc::clone(&local_port)),
|
||||||
|
(DEFAULT_HOSTED_MODEL_PREFIX.to_owned(), Arc::clone(&hosted_port)),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
assert!(Arc::ptr_eq(
|
||||||
|
routed.route("claude-opus-5-5").unwrap(),
|
||||||
|
&connector_port
|
||||||
|
));
|
||||||
|
assert!(Arc::ptr_eq(
|
||||||
|
routed.route("local/llama-8b").unwrap(),
|
||||||
|
&local_port
|
||||||
|
));
|
||||||
|
assert!(Arc::ptr_eq(
|
||||||
|
routed.route("hosted/deepseek-chat").unwrap(),
|
||||||
|
&hosted_port
|
||||||
|
));
|
||||||
|
|
||||||
|
let clashing_local = LocalBinding {
|
||||||
|
endpoint: "127.0.0.1:9".parse().unwrap(),
|
||||||
|
model_prefix: "shared/".into(),
|
||||||
|
caller_runtime_id: TEST_RUNTIME.into(),
|
||||||
|
};
|
||||||
|
let clashing_hosted = HostedBinding {
|
||||||
|
base_url: "https://api.example.test".into(),
|
||||||
|
key_path: hosted_key,
|
||||||
|
model_prefix: "shared/".into(),
|
||||||
|
caller_runtime_id: TEST_RUNTIME.into(),
|
||||||
|
};
|
||||||
|
assert!(matches!(
|
||||||
|
open_inference(None, Some(clashing_local), Some(clashing_hosted), &["shared/x"]),
|
||||||
|
Err(ControllerOpenError::SharedModelPrefix { prefix }) if prefix == "shared/"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Spec test 12.
|
||||||
|
#[test]
|
||||||
|
fn a_model_prefix_routes_a_lane_to_its_port() {
|
||||||
|
let claimed = Arc::new(StubPort) as Arc<dyn InferencePort>;
|
||||||
|
let connector = Arc::new(StubPort) as Arc<dyn InferencePort>;
|
||||||
|
let routed = RoutedInferencePort::new(
|
||||||
|
Some(Arc::clone(&connector)),
|
||||||
|
vec![("local/".to_owned(), Arc::clone(&claimed))],
|
||||||
|
);
|
||||||
|
assert!(Arc::ptr_eq(
|
||||||
|
routed.route("local/llama-8b").unwrap(),
|
||||||
|
&claimed
|
||||||
|
));
|
||||||
|
assert!(Arc::ptr_eq(
|
||||||
|
routed.route("claude-opus-5-5").unwrap(),
|
||||||
|
&connector
|
||||||
|
));
|
||||||
|
assert!(Arc::ptr_eq(
|
||||||
|
routed.route("gpt-5.6-terra").unwrap(),
|
||||||
|
&connector
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Spec test 13.
|
||||||
|
#[test]
|
||||||
|
fn an_unroutable_model_fails_at_open() {
|
||||||
|
let directory = tempfile::tempdir().unwrap();
|
||||||
|
let key = directory.path().join("controller.key");
|
||||||
|
std::fs::write(&key, "routed-port-test-key").unwrap();
|
||||||
|
let connector = || ConnectorBinding {
|
||||||
|
endpoint: "127.0.0.1:9".parse().unwrap(),
|
||||||
|
key_path: key.clone(),
|
||||||
|
caller_runtime_id: TEST_RUNTIME.into(),
|
||||||
|
};
|
||||||
|
let local = || LocalBinding {
|
||||||
|
endpoint: "127.0.0.1:9".parse().unwrap(),
|
||||||
|
model_prefix: DEFAULT_LOCAL_MODEL_PREFIX.into(),
|
||||||
|
caller_runtime_id: TEST_RUNTIME.into(),
|
||||||
|
};
|
||||||
|
|
||||||
|
assert!(matches!(
|
||||||
|
open_inference(None, Some(local()), None, &models("gpt-5.6-terra").each()),
|
||||||
|
Err(ControllerOpenError::UnroutableModel { .. })
|
||||||
|
));
|
||||||
|
// The connector serves any model no local or hosted prefix claims.
|
||||||
|
assert!(
|
||||||
|
open_inference(Some(connector()), None, None, &models("claude-haiku-5-5").each()).is_ok()
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
open_inference(Some(connector()), None, None, &models("claude-opus-5").each()).is_ok()
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
open_inference(Some(connector()), None, None, &models(TEST_MODEL).each()).is_ok(),
|
||||||
|
"a configuration where every model routes did not open"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Soul: an unroutable model is refused at `infer` as well as at open.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn soul_routing_refuses_rather_than_falling_back() {
|
||||||
|
let connector = Arc::new(StubPort) as Arc<dyn InferencePort>;
|
||||||
|
let connector_only = RoutedInferencePort::new(Some(Arc::clone(&connector)), Vec::new());
|
||||||
|
assert!(Arc::ptr_eq(
|
||||||
|
connector_only.route(TEST_MODEL).unwrap(),
|
||||||
|
&connector
|
||||||
|
));
|
||||||
|
// A prefix that does not match, and no connector: the model has no
|
||||||
|
// owner and routes nowhere.
|
||||||
|
let unclaimed = RoutedInferencePort::new(
|
||||||
|
None,
|
||||||
|
vec![("hosted/".to_owned(), Arc::new(StubPort) as Arc<dyn InferencePort>)],
|
||||||
|
);
|
||||||
|
assert!(unclaimed.route(TEST_MODEL).is_none());
|
||||||
|
let prepared =
|
||||||
|
PreparedInference::prepare(TEST_RUNTIME, 4_102_444_800_000, prose_request("Say it."))
|
||||||
|
.unwrap();
|
||||||
|
for fault in [
|
||||||
|
unclaimed
|
||||||
|
.prepare(prose_request("Say it."))
|
||||||
|
.expect_err("an unroutable model prepared"),
|
||||||
|
unclaimed
|
||||||
|
.infer(prepared)
|
||||||
|
.await
|
||||||
|
.expect_err("an unroutable model inferred"),
|
||||||
|
] {
|
||||||
|
assert!(fault.integrity_was_violated(), "{fault:?}");
|
||||||
|
assert!(
|
||||||
|
fault.to_string().contains("no configured inference backend"),
|
||||||
|
"{fault:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -14,7 +14,7 @@
|
||||||
//! Projector may call it.
|
//! Projector may call it.
|
||||||
|
|
||||||
use super::controllers::{
|
use super::controllers::{
|
||||||
self, ControllerError, InferenceEvent, InferenceOutput, InferencePurpose, InferenceRequest,
|
self, ControllerError, InferenceEvent, InferenceOutput, InferencePurpose, InferenceRequest, TokenUsage,
|
||||||
RequestShape, tool_request,
|
RequestShape, tool_request,
|
||||||
};
|
};
|
||||||
use super::patch::{
|
use super::patch::{
|
||||||
|
|
@ -26,7 +26,7 @@ use super::{
|
||||||
DecisionOpportunity, EntityId, KernelError, Mismatch, RefKind, Statement, SubjectId,
|
DecisionOpportunity, EntityId, KernelError, Mismatch, RefKind, Statement, SubjectId,
|
||||||
SubjectKind, Target, WorldPatch, WorldSnapshot,
|
SubjectKind, Target, WorldPatch, WorldSnapshot,
|
||||||
};
|
};
|
||||||
use codex_connector::{CodexInputItem, CodexToolDefinition};
|
use model_connector::{InputItem, ToolDefinition};
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
|
|
||||||
|
|
@ -44,7 +44,7 @@ pub enum TableError {
|
||||||
/// `PATCH_TOOLS`; which names a particular agent gets is policy, and policy
|
/// `PATCH_TOOLS`; which names a particular agent gets is policy, and policy
|
||||||
/// belongs to the caller — `PLAY_TOOLS` is Dungeon's, pinned in Cut 8, not
|
/// belongs to the caller — `PLAY_TOOLS` is Dungeon's, pinned in Cut 8, not
|
||||||
/// this module's.
|
/// this module's.
|
||||||
pub fn authoring_tools(names: &[&str]) -> Result<Vec<CodexToolDefinition>, TableError> {
|
pub fn authoring_tools(names: &[&str]) -> Result<Vec<ToolDefinition>, TableError> {
|
||||||
let catalog = patch::patch_tools();
|
let catalog = patch::patch_tools();
|
||||||
names
|
names
|
||||||
.iter()
|
.iter()
|
||||||
|
|
@ -220,7 +220,7 @@ fn subject_opportunity<'a>(
|
||||||
/// turn; that is the controller lane's own vocabulary, and
|
/// turn; that is the controller lane's own vocabulary, and
|
||||||
/// `decode_actor_call` has no arm for either, so offering them here would
|
/// `decode_actor_call` has no arm for either, so offering them here would
|
||||||
/// hand the play agent a tool `decode_actor_call` always refuses (PA.f55).
|
/// hand the play agent a tool `decode_actor_call` always refuses (PA.f55).
|
||||||
pub fn actor_tools(prefix: &str, snapshot: &WorldSnapshot, subject: SubjectId) -> Vec<CodexToolDefinition> {
|
pub fn actor_tools(prefix: &str, snapshot: &WorldSnapshot, subject: SubjectId) -> Vec<ToolDefinition> {
|
||||||
match subject_opportunity(snapshot, subject) {
|
match subject_opportunity(snapshot, subject) {
|
||||||
Some((_, granted)) => controllers::affordance_tools(prefix, &granted),
|
Some((_, granted)) => controllers::affordance_tools(prefix, &granted),
|
||||||
None => Vec::new(),
|
None => Vec::new(),
|
||||||
|
|
@ -983,6 +983,100 @@ fn render_dependency_target(snapshot: &WorldSnapshot, target: &DependencyTarget)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The wrongs the world holds against a subject and what has answered them,
|
||||||
|
/// read off state and stored nowhere: whom the doer wronged (a grievance in the
|
||||||
|
/// victim's regard), who saw the doer's acts (`Seen` knowledge), which forums
|
||||||
|
/// cover the doer, who presses the doer, and who has sworn a reckoning with the
|
||||||
|
/// doer as counterparty. A grievance nothing answers is named as unanswered:
|
||||||
|
/// the table's own judgement sends the watch, so what it needs is to see that
|
||||||
|
/// no one has been sent.
|
||||||
|
fn render_open_grievances(snapshot: &WorldSnapshot) -> String {
|
||||||
|
use crate::attitude::AttitudeCause;
|
||||||
|
use crate::patch::KnowledgeSource;
|
||||||
|
let name = |id: SubjectId| {
|
||||||
|
label_for_any_id(snapshot, &id_text(id)).unwrap_or_else(|| format!("[{}]", id_text(id)))
|
||||||
|
};
|
||||||
|
let mut out = String::from("\n Open grievances (derived: who was wronged, who saw it, what answers it):");
|
||||||
|
let mut any = false;
|
||||||
|
for doer in &snapshot.subjects {
|
||||||
|
let wronged: Vec<String> = snapshot
|
||||||
|
.subjects
|
||||||
|
.iter()
|
||||||
|
.flat_map(|holder| {
|
||||||
|
holder
|
||||||
|
.opinions
|
||||||
|
.iter()
|
||||||
|
.filter(|held| held.toward == doer.id)
|
||||||
|
.filter(|held| {
|
||||||
|
held.causes
|
||||||
|
.iter()
|
||||||
|
.any(|cause| matches!(cause.cause, AttitudeCause::Grievance { .. }) && cause.delta < 0)
|
||||||
|
})
|
||||||
|
.map(|held| format!("{} ({:+})", name(holder.id), held.total))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
if wronged.is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
any = true;
|
||||||
|
let mut seen_by = Vec::new();
|
||||||
|
let mut acts = std::collections::BTreeSet::new();
|
||||||
|
for witness in snapshot.subjects.iter().filter(|witness| witness.id != doer.id) {
|
||||||
|
for row in &witness.knowledge {
|
||||||
|
if row.source == (KnowledgeSource::Seen { by: doer.id }) {
|
||||||
|
seen_by.push(name(witness.id));
|
||||||
|
acts.insert(format!("\"{}\"", row.statement.as_str()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
seen_by.sort();
|
||||||
|
seen_by.dedup();
|
||||||
|
let pressing: Vec<String> = doer
|
||||||
|
.pressures
|
||||||
|
.iter()
|
||||||
|
.filter_map(|pressure| match pressure.source {
|
||||||
|
PressureSource::Subject(id) => Some(format!("{} ({})", name(id), pressure.magnitude.0)),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let reckonings: Vec<String> = snapshot
|
||||||
|
.subjects
|
||||||
|
.iter()
|
||||||
|
.flat_map(|holder| {
|
||||||
|
holder
|
||||||
|
.commitments
|
||||||
|
.iter()
|
||||||
|
.filter(|commitment| commitment.counterparty == Some(doer.id))
|
||||||
|
.map(move |commitment| format!("{}: \"{}\"", name(holder.id), commitment.statement.as_str()))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let answered = !pressing.is_empty() || !reckonings.is_empty();
|
||||||
|
out.push_str(&format!(
|
||||||
|
" {} wronged {}; acts seen by: {}{}; forums covering them: {}; pressed by: {}; reckonings sworn against them: {}; {}",
|
||||||
|
name(doer.id),
|
||||||
|
joined_sorted(wronged),
|
||||||
|
if seen_by.is_empty() { "no one".to_owned() } else { joined_sorted(seen_by) },
|
||||||
|
if acts.is_empty() { String::new() } else { format!(" ({})", joined_sorted(acts.into_iter().collect())) },
|
||||||
|
if doer.redress.is_empty() {
|
||||||
|
"none".to_owned()
|
||||||
|
} else {
|
||||||
|
joined_sorted(doer.redress.iter().map(|forum| render_forum(snapshot, forum)).collect())
|
||||||
|
},
|
||||||
|
if pressing.is_empty() { "no one".to_owned() } else { joined_sorted(pressing) },
|
||||||
|
if reckonings.is_empty() { "none".to_owned() } else { joined_sorted(reckonings) },
|
||||||
|
if answered {
|
||||||
|
"answered so far."
|
||||||
|
} else {
|
||||||
|
"nothing has answered it yet: no office presses them and no kin or ally has sworn anything. The office, the kin and the witnesses answer through their own people: dispatch them, or rule it with advance_pressure and create_commitment."
|
||||||
|
},
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if !any {
|
||||||
|
out.push_str(" none");
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
/// A pressure source, in the same shape `advance_pressure`/`reduce_pressure`'s
|
/// A pressure source, in the same shape `advance_pressure`/`reduce_pressure`'s
|
||||||
/// `PressureSourceRef` composite takes: a commitment names the promisor
|
/// `PressureSourceRef` composite takes: a commitment names the promisor
|
||||||
/// subject id and the commitment key; a dependency names its target; a
|
/// subject id and the commitment key; a dependency names its target; a
|
||||||
|
|
@ -1038,8 +1132,8 @@ impl InferenceRequest {
|
||||||
round: usize,
|
round: usize,
|
||||||
model: &str,
|
model: &str,
|
||||||
instructions: &str,
|
instructions: &str,
|
||||||
input: Vec<CodexInputItem>,
|
input: Vec<InputItem>,
|
||||||
tools: Vec<CodexToolDefinition>,
|
tools: Vec<ToolDefinition>,
|
||||||
max_output_tokens: u32,
|
max_output_tokens: u32,
|
||||||
) -> Result<InferenceRequest, ControllerError> {
|
) -> Result<InferenceRequest, ControllerError> {
|
||||||
tool_request(
|
tool_request(
|
||||||
|
|
@ -1070,6 +1164,12 @@ impl InferenceOutput {
|
||||||
pub fn receipt_digest(&self) -> &str {
|
pub fn receipt_digest(&self) -> &str {
|
||||||
&self.receipt_digest
|
&self.receipt_digest
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The tokens the provider reported for this reply; `None` when it
|
||||||
|
/// reported none.
|
||||||
|
pub fn usage(&self) -> Option<TokenUsage> {
|
||||||
|
self.usage
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The canonical id as the patch vocabulary spells it: the bare UUID text,
|
/// The canonical id as the patch vocabulary spells it: the bare UUID text,
|
||||||
|
|
@ -1089,6 +1189,17 @@ pub fn id_text(id: impl std::fmt::Debug) -> String {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A subject's own short handle: the first 8 hex digits of its id. Actor tool
|
||||||
|
/// names are `<handle>__<kind>` and a kind may run to 48 chars, so the full id
|
||||||
|
/// text would break a common 64-char function-name limit; the Gestalt round's
|
||||||
|
/// section headers carry the same handle, so a reply splits on a token that
|
||||||
|
/// names exactly one subject even when two share a label. A collision between
|
||||||
|
/// two subjects is astronomically unlikely but not impossible; each caller that
|
||||||
|
/// keys on handles refuses it rather than addressing the wrong subject.
|
||||||
|
pub fn handle_for(id: crate::SubjectId) -> String {
|
||||||
|
id_text(id).chars().filter(char::is_ascii_hexdigit).take(8).collect()
|
||||||
|
}
|
||||||
|
|
||||||
/// The parser matching `id_text` above (PA.f113): `text` names `id` only
|
/// The parser matching `id_text` above (PA.f113): `text` names `id` only
|
||||||
/// when it is exactly the bytes `id_text(id)` would print — no brackets, no
|
/// when it is exactly the bytes `id_text(id)` would print — no brackets, no
|
||||||
/// padding, no case folding, because this is plain string equality against
|
/// padding, no case folding, because this is plain string equality against
|
||||||
|
|
@ -1102,7 +1213,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 {
|
||||||
|
|
@ -1541,6 +1652,44 @@ pub fn table_view(snapshot: &WorldSnapshot) -> String {
|
||||||
out.push_str(" none");
|
out.push_str(" none");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Derived by the kernel from sourced modifiers; the one reading the
|
||||||
|
// Persona's own view and the narrator also draw from. A prejudice toward a
|
||||||
|
// trait shows only once its holder knows the subject carries it.
|
||||||
|
out.push_str("\n Regard (how each subject holds another, with what it rests on):");
|
||||||
|
let mut any_regard = false;
|
||||||
|
for subject in &snapshot.subjects {
|
||||||
|
for held in &subject.opinions {
|
||||||
|
any_regard = true;
|
||||||
|
let toward = label_for_any_id(snapshot, &id_text(held.toward))
|
||||||
|
.unwrap_or_else(|| format!("[{}]", id_text(held.toward)));
|
||||||
|
out.push_str(&format!(
|
||||||
|
" {} [{}] regards {} with {} ({:+}): {};",
|
||||||
|
subject.label,
|
||||||
|
id_text(subject.id),
|
||||||
|
toward,
|
||||||
|
crate::attitude::regard_word(held.total),
|
||||||
|
held.total,
|
||||||
|
joined(
|
||||||
|
held.causes
|
||||||
|
.iter()
|
||||||
|
.map(|cause| crate::attitude::describe_cause(cause, |fact| {
|
||||||
|
snapshot
|
||||||
|
.facts
|
||||||
|
.iter()
|
||||||
|
.find(|entry| entry.id == fact)
|
||||||
|
.map(|entry| entry.statement.as_str().to_owned())
|
||||||
|
}))
|
||||||
|
.collect()
|
||||||
|
)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !any_regard {
|
||||||
|
out.push_str(" none");
|
||||||
|
}
|
||||||
|
|
||||||
|
out.push_str(&render_open_grievances(snapshot));
|
||||||
|
|
||||||
out.push_str("\n Persona material:");
|
out.push_str("\n Persona material:");
|
||||||
let mut any_material = false;
|
let mut any_material = false;
|
||||||
for subject in &snapshot.subjects {
|
for subject in &snapshot.subjects {
|
||||||
|
|
@ -1585,7 +1734,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
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1600,7 +1749,8 @@ mod tests {
|
||||||
// PA.f75: `communicate` was removed from `PLAY_TOOLS`; Dungeon drops it
|
// PA.f75: `communicate` was removed from `PLAY_TOOLS`; Dungeon drops it
|
||||||
// from its own list too. This is now the complete 24-tool list.
|
// from its own list too. This is now the complete 24-tool list.
|
||||||
// PA.f88: this is the library's own test fixture, kept in sync by hand.
|
// PA.f88: this is the library's own test fixture, kept in sync by hand.
|
||||||
// Dungeon's `PLAY_TOOLS` in `ghostlight-dungeon/src/play.rs` is the
|
// Dungeon's `PLAY_TOOLS` in `ghostlight-dungeon/src/play.rs` (parked at
|
||||||
|
// `parked/ghostlight-eve-surface`) is the
|
||||||
// single policy owner of what the play agent may actually call; this
|
// single policy owner of what the play agent may actually call; this
|
||||||
// copy pins nothing there and is not read by production code.
|
// copy pins nothing there and is not read by production code.
|
||||||
const PLAY_TOOLS: &[&str] = &[
|
const PLAY_TOOLS: &[&str] = &[
|
||||||
|
|
@ -2489,6 +2639,7 @@ mod tests {
|
||||||
outcome_bands: Vec::new(),
|
outcome_bands: Vec::new(),
|
||||||
carries_speech: false,
|
carries_speech: false,
|
||||||
},
|
},
|
||||||
|
render_path: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -3113,7 +3264,7 @@ mod tests {
|
||||||
("local_inference.rs", include_str!("local_inference.rs")),
|
("local_inference.rs", include_str!("local_inference.rs")),
|
||||||
("mailbox.rs", include_str!("mailbox.rs")),
|
("mailbox.rs", include_str!("mailbox.rs")),
|
||||||
("patch.rs", include_str!("patch.rs")),
|
("patch.rs", include_str!("patch.rs")),
|
||||||
("sdk_inference.rs", include_str!("sdk_inference.rs")),
|
("routed_inference.rs", include_str!("routed_inference.rs")),
|
||||||
("tool_schema.rs", include_str!("tool_schema.rs")),
|
("tool_schema.rs", include_str!("tool_schema.rs")),
|
||||||
("vault.rs", include_str!("vault.rs")),
|
("vault.rs", include_str!("vault.rs")),
|
||||||
];
|
];
|
||||||
|
|
|
||||||
|
|
@ -6,11 +6,11 @@
|
||||||
//! own vocabulary. Both spell a property the same way because both spell it
|
//! own vocabulary. Both spell a property the same way because both spell it
|
||||||
//! here. Nothing in this module reads world state, a snapshot, or a config.
|
//! here. Nothing in this module reads world state, a snapshot, or a config.
|
||||||
|
|
||||||
use codex_connector::CodexToolDefinition;
|
use model_connector::ToolDefinition;
|
||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
pub(super) fn tool(name: &str, description: &str, schema: Value) -> CodexToolDefinition {
|
pub(super) fn tool(name: &str, description: &str, schema: Value) -> ToolDefinition {
|
||||||
CodexToolDefinition {
|
ToolDefinition {
|
||||||
name: name.into(),
|
name: name.into(),
|
||||||
description: description.into(),
|
description: description.into(),
|
||||||
parameters_json: serde_json::to_string(&schema)
|
parameters_json: serde_json::to_string(&schema)
|
||||||
|
|
@ -43,10 +43,29 @@ pub(super) fn canonical_string(description: &str) -> Value {
|
||||||
json!({"type": "string", "description": description})
|
json!({"type": "string", "description": description})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A string the kernel will hold to its civic-name rule, `[a-z][a-z0-9_]` up to
|
||||||
|
/// `max` characters. The rule is stated twice on purpose: as a `pattern` a
|
||||||
|
/// strict decoder can enforce, and in the description the model reads. `max` is
|
||||||
|
/// the kernel's own bound, passed in so the rule has one owner.
|
||||||
|
pub(super) fn civic_name(description: &str, max: usize) -> Value {
|
||||||
|
json!({
|
||||||
|
"type": "string",
|
||||||
|
"pattern": format!("^[a-z][a-z0-9_]{{0,{}}}$", max - 1),
|
||||||
|
"description": format!(
|
||||||
|
"{description}: lowercase snake_case, starting with a letter, at most {max} characters (e.g. toll_command)"
|
||||||
|
),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
pub(super) fn bounded_integer(min: u64, max: u64) -> Value {
|
pub(super) fn bounded_integer(min: u64, max: u64) -> Value {
|
||||||
json!({"type": "integer", "minimum": min, "maximum": max})
|
json!({"type": "integer", "minimum": min, "maximum": max})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// An integer that may be negative, for a regard that can fall as well as rise.
|
||||||
|
pub(super) fn signed_integer(min: i64, max: i64) -> Value {
|
||||||
|
json!({"type": "integer", "minimum": min, "maximum": max})
|
||||||
|
}
|
||||||
|
|
||||||
/// The same schema with the text the model reads beside it. Meaning that lives
|
/// The same schema with the text the model reads beside it. Meaning that lives
|
||||||
/// only in a prompt paragraph is lost by the time the model fills the field.
|
/// only in a prompt paragraph is lost by the time the model fills the field.
|
||||||
pub(super) fn described(mut schema: Value, description: &str) -> Value {
|
pub(super) fn described(mut schema: Value, description: &str) -> Value {
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load diff
984
crates/ghostlight/src/verse/calls.rs
Normal file
984
crates/ghostlight/src/verse/calls.rs
Normal file
|
|
@ -0,0 +1,984 @@
|
||||||
|
//! Provider call records, the run's spend, and replay.
|
||||||
|
//!
|
||||||
|
//! `RecordingInferencePort` is the one owner of a run's spend. Before it
|
||||||
|
//! forwards a call it decides, from the request alone, whether the call could
|
||||||
|
//! pass the run's token cap; after the reply it charges what the call really
|
||||||
|
//! cost. Every reply is stored as a `ProviderCallRecord` before the output
|
||||||
|
//! returns to the lane, so `ReplayInferencePort` can serve the same run again
|
||||||
|
//! from the store with no provider behind it.
|
||||||
|
//!
|
||||||
|
//! Lanes and runners never count tokens. A request is held against the cap by
|
||||||
|
//! its bound: the serialized provider request's bytes (a token is at least one
|
||||||
|
//! byte, so bytes bound the prompt) plus the request's own output allowance.
|
||||||
|
//!
|
||||||
|
//! The run's spend is one persisted ledger row per run, owned by the store and
|
||||||
|
//! written where it is spent. A call reserves its bound in that row before the
|
||||||
|
//! provider is called; a reply settles the reservation to what it reported
|
||||||
|
//! (prompt plus completion, cached prompt tokens being part of the prompt; none
|
||||||
|
//! reported is charged the bound); a fault leaves the reservation charged. A
|
||||||
|
//! restart reads the row, so no restart returns budget. A reply that reports
|
||||||
|
//! more than the call's bound is charged in full and faults the call, so the
|
||||||
|
//! run's spend never passes the cap unnoticed. One port at a time owns a run.
|
||||||
|
|
||||||
|
use crate::controllers::{
|
||||||
|
ControllerError, InferenceEvent, InferenceFault, InferenceOutput, InferencePort,
|
||||||
|
InferencePurpose, InferenceRequest, PreparedInference, REQUEST_EXPIRY, TokenUsage,
|
||||||
|
request_id_prefix, unix_ms,
|
||||||
|
};
|
||||||
|
use crate::{FrozenCell, NodeId, TickIndex, WorldId};
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use chrono::Utc;
|
||||||
|
use model_connector::ProviderRequest;
|
||||||
|
use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
use std::{
|
||||||
|
collections::{BTreeMap, BTreeSet, VecDeque},
|
||||||
|
path::Path,
|
||||||
|
sync::{Arc, Mutex},
|
||||||
|
};
|
||||||
|
use thiserror::Error;
|
||||||
|
|
||||||
|
const CALL_RECORD_ROW: &str = "verse_provider_call.v2";
|
||||||
|
const RUN_LEDGER_ROW: &str = "verse_run_ledger.v2";
|
||||||
|
/// The run ledger document's schema.
|
||||||
|
const RUN_LEDGER_SCHEMA: &str = "ghostlight.verse_run_ledger.v2";
|
||||||
|
/// The call record document's schema. A store holding any other row type or
|
||||||
|
/// schema is refused at open: this store is not migrated from, or shared with,
|
||||||
|
/// another document.
|
||||||
|
pub const CALL_RECORD_SCHEMA: &str = "ghostlight.verse_provider_call.v2";
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, Error, PartialEq, Eq)]
|
||||||
|
pub enum CallRecordError {
|
||||||
|
#[error("a run id is 1 to 64 characters of letters, digits, '-' and '_'")]
|
||||||
|
InvalidRunId,
|
||||||
|
#[error("the call record store could not be read or written")]
|
||||||
|
Store,
|
||||||
|
#[error("the call record store holds a row that is not a canonical call record")]
|
||||||
|
Corrupt,
|
||||||
|
#[error("a call record's sequence is not the next in its run")]
|
||||||
|
OutOfSequence,
|
||||||
|
#[error("replay needs one run's records in dense sequence from 1")]
|
||||||
|
NotReplayable,
|
||||||
|
#[error("another recording port already owns this run")]
|
||||||
|
RunInUse,
|
||||||
|
#[error("the call could pass the run's token cap")]
|
||||||
|
OverCap,
|
||||||
|
#[error("the call could pass its lane's allowance")]
|
||||||
|
OverAllowance,
|
||||||
|
#[error("the run was recorded with a different {0}")]
|
||||||
|
RunMismatch(RunField),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a run is bound to when it begins, named by the field a mismatch refuses.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum RunField {
|
||||||
|
/// The token cap the run was opened with.
|
||||||
|
Cap,
|
||||||
|
/// The lane allowances the run was opened with.
|
||||||
|
Allowances,
|
||||||
|
/// The identity of the world the run started from.
|
||||||
|
WorldId,
|
||||||
|
/// The state digest of the world the run started from.
|
||||||
|
StateDigest,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Display for RunField {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.write_str(match self {
|
||||||
|
Self::Cap => "token cap",
|
||||||
|
Self::Allowances => "lane allowances",
|
||||||
|
Self::WorldId => "world id",
|
||||||
|
Self::StateDigest => "world state digest",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The background lane a metered call spends in. The room lane, the DM's play
|
||||||
|
/// turn, is in no window: it is never reserved here.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||||
|
pub enum Lane {
|
||||||
|
/// A node turn of a Gestalt wave.
|
||||||
|
Wave,
|
||||||
|
/// An elaborator session.
|
||||||
|
Elaboration,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Lane {
|
||||||
|
/// The lane a call of this purpose spends in; the play agent has none.
|
||||||
|
pub fn of(purpose: InferencePurpose) -> Option<Self> {
|
||||||
|
match purpose {
|
||||||
|
InferencePurpose::Play => None,
|
||||||
|
InferencePurpose::Elaboration => Some(Self::Elaboration),
|
||||||
|
_ => Some(Self::Wave),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tokens by lane: a window's allowances, or what its lanes have reserved or
|
||||||
|
/// been charged.
|
||||||
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct LaneTokens {
|
||||||
|
pub wave: u64,
|
||||||
|
pub elaboration: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LaneTokens {
|
||||||
|
pub fn of(&self, lane: Lane) -> u64 {
|
||||||
|
match lane {
|
||||||
|
Lane::Wave => self.wave,
|
||||||
|
Lane::Elaboration => self.elaboration,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set(&mut self, lane: Lane, tokens: u64) {
|
||||||
|
match lane {
|
||||||
|
Lane::Wave => self.wave = tokens,
|
||||||
|
Lane::Elaboration => self.elaboration = tokens,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every lane together.
|
||||||
|
pub fn total(&self) -> u64 {
|
||||||
|
self.wave.saturating_add(self.elaboration)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The world a run began from: its identity and state digest. Replay is of a
|
||||||
|
/// restored copy of this world, so it takes the same two values.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct RunStart {
|
||||||
|
world_id: String,
|
||||||
|
state_digest: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RunStart {
|
||||||
|
pub fn of(world: &crate::WorldSnapshot) -> Self {
|
||||||
|
Self {
|
||||||
|
world_id: world.world_id.text(),
|
||||||
|
state_digest: world.state_digest.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A run's identity as a key segment.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||||
|
pub struct RunId(String);
|
||||||
|
|
||||||
|
impl RunId {
|
||||||
|
pub fn new(id: &str) -> Result<Self, CallRecordError> {
|
||||||
|
let valid = !id.is_empty()
|
||||||
|
&& id.len() <= 64
|
||||||
|
&& id
|
||||||
|
.bytes()
|
||||||
|
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_');
|
||||||
|
if valid {
|
||||||
|
Ok(Self(id.to_owned()))
|
||||||
|
} else {
|
||||||
|
Err(CallRecordError::InvalidRunId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn as_str(&self) -> &str {
|
||||||
|
&self.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One provider call of one run: the request's content digest (never its text, so no
|
||||||
|
/// prompt or credential is stored), the reply exactly as the lane received it,
|
||||||
|
/// and what the call was charged. Keyed (run id, sequence).
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct ProviderCallRecord {
|
||||||
|
run_id: String,
|
||||||
|
sequence: u64,
|
||||||
|
purpose: InferencePurpose,
|
||||||
|
lane: Lane,
|
||||||
|
request_id: String,
|
||||||
|
model: String,
|
||||||
|
content_sha256: String,
|
||||||
|
events: Vec<InferenceEvent>,
|
||||||
|
receipt_digest: String,
|
||||||
|
usage: Option<TokenUsage>,
|
||||||
|
charged: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ProviderCallRecord {
|
||||||
|
pub fn run_id(&self) -> &str {
|
||||||
|
&self.run_id
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn sequence(&self) -> u64 {
|
||||||
|
self.sequence
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn purpose(&self) -> InferencePurpose {
|
||||||
|
self.purpose
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The lane this call spent in.
|
||||||
|
pub fn lane(&self) -> Lane {
|
||||||
|
self.lane
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The provider request id, which carries the command id it ran under: the
|
||||||
|
/// join from a call to the wave cell that made it.
|
||||||
|
pub fn request_id(&self) -> &str {
|
||||||
|
&self.request_id
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn model(&self) -> &str {
|
||||||
|
&self.model
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Lowercase hex of the request's content digest (see `content_digest`).
|
||||||
|
pub fn content_sha256(&self) -> &str {
|
||||||
|
&self.content_sha256
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn usage(&self) -> Option<TokenUsage> {
|
||||||
|
self.usage
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tokens this call was charged against the run's cap.
|
||||||
|
pub fn charged(&self) -> u64 {
|
||||||
|
self.charged
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The reply as the lane received it.
|
||||||
|
pub fn output(&self) -> InferenceOutput {
|
||||||
|
let output = InferenceOutput::new(self.events.clone(), self.receipt_digest.clone());
|
||||||
|
match self.usage {
|
||||||
|
Some(usage) => output.with_usage(usage),
|
||||||
|
None => output,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn row_key(run: &str, sequence: u64) -> String {
|
||||||
|
format!("{run}/{sequence:020}")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hex(digest: &[u8]) -> String {
|
||||||
|
digest.iter().map(|byte| format!("{byte:02x}")).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a request asks of the provider, without the ids that name it. The
|
||||||
|
/// request and conversation ids are derived from the command id, and a command
|
||||||
|
/// id from the world it ran in, so keying on them would tie a recorded run to
|
||||||
|
/// one world's random identity. Everything else the provider is sent
|
||||||
|
/// (model, instructions, input, tools, shape) is in the digest.
|
||||||
|
fn content_digest(request: &ProviderRequest) -> Result<String, InferenceFault> {
|
||||||
|
// Exhaustive on purpose: a field added upstream must be placed in the key
|
||||||
|
// or left out here by name before this compiles.
|
||||||
|
let ProviderRequest {
|
||||||
|
schema_id,
|
||||||
|
request_id: _request_id, // names the call, not what it asks
|
||||||
|
conversation_id: _conversation_id, // names the call, not what it asks
|
||||||
|
model,
|
||||||
|
instructions,
|
||||||
|
input,
|
||||||
|
reasoning_effort,
|
||||||
|
cache_retention,
|
||||||
|
tools,
|
||||||
|
tool_choice,
|
||||||
|
parallel_tool_calls,
|
||||||
|
output_schema_json,
|
||||||
|
max_output_tokens,
|
||||||
|
} = request;
|
||||||
|
let bytes = rmp_serde::to_vec(&(
|
||||||
|
schema_id,
|
||||||
|
model,
|
||||||
|
instructions,
|
||||||
|
input,
|
||||||
|
reasoning_effort,
|
||||||
|
cache_retention,
|
||||||
|
tools,
|
||||||
|
tool_choice,
|
||||||
|
parallel_tool_calls,
|
||||||
|
output_schema_json,
|
||||||
|
max_output_tokens,
|
||||||
|
))
|
||||||
|
.map_err(|_| InferenceFault::new("a provider request could not be measured"))?;
|
||||||
|
Ok(hex(&Sha256::digest(bytes)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A run's persisted ledger, the one owner of what the run began as: the cap
|
||||||
|
/// it was opened under, the world it started from, and the tokens reserved or
|
||||||
|
/// charged so far.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
struct RunLedger {
|
||||||
|
run_id: String,
|
||||||
|
cap: u64,
|
||||||
|
allowances: LaneTokens,
|
||||||
|
start: RunStart,
|
||||||
|
/// Tokens reserved or charged, by lane. The run's spend is their sum.
|
||||||
|
spent: LaneTokens,
|
||||||
|
}
|
||||||
|
|
||||||
|
enum DecodedRow {
|
||||||
|
Call(ProviderCallRecord),
|
||||||
|
Ledger(RunLedger),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn canonical<T: Serialize + for<'de> Deserialize<'de>>(
|
||||||
|
row: &CultCacheEnvelope,
|
||||||
|
) -> Result<T, CallRecordError> {
|
||||||
|
let value: T = rmp_serde::from_slice(&row.payload).map_err(|_| CallRecordError::Corrupt)?;
|
||||||
|
let again = rmp_serde::to_vec_named(&value).map_err(|_| CallRecordError::Corrupt)?;
|
||||||
|
if again == row.payload {
|
||||||
|
Ok(value)
|
||||||
|
} else {
|
||||||
|
Err(CallRecordError::Corrupt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn decode_row(row: &CultCacheEnvelope) -> Result<DecodedRow, CallRecordError> {
|
||||||
|
match (row.r#type.as_str(), row.schema_id.as_deref()) {
|
||||||
|
(CALL_RECORD_ROW, Some(CALL_RECORD_SCHEMA)) => {
|
||||||
|
let record: ProviderCallRecord = canonical(row)?;
|
||||||
|
// A run id that is no whole key segment would key into another
|
||||||
|
// run's records, and sequences count from 1.
|
||||||
|
if RunId::new(&record.run_id).is_err()
|
||||||
|
|| record.sequence == 0
|
||||||
|
|| row.key != row_key(&record.run_id, record.sequence)
|
||||||
|
{
|
||||||
|
return Err(CallRecordError::Corrupt);
|
||||||
|
}
|
||||||
|
Ok(DecodedRow::Call(record))
|
||||||
|
}
|
||||||
|
(RUN_LEDGER_ROW, Some(RUN_LEDGER_SCHEMA)) => {
|
||||||
|
let ledger: RunLedger = canonical(row)?;
|
||||||
|
if RunId::new(&ledger.run_id).is_err() || row.key != ledger.run_id {
|
||||||
|
return Err(CallRecordError::Corrupt);
|
||||||
|
}
|
||||||
|
Ok(DecodedRow::Ledger(ledger))
|
||||||
|
}
|
||||||
|
_ => Err(CallRecordError::Corrupt),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct RunTally {
|
||||||
|
last_sequence: u64,
|
||||||
|
/// The persisted ledger, read at open and written where it is spent.
|
||||||
|
ledger: Option<RunLedger>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct StoreState {
|
||||||
|
store: OwnedRedbMessagePackBackingStore,
|
||||||
|
runs: BTreeMap<String, RunTally>,
|
||||||
|
/// Runs with a recording port alive; one ledger has one owner.
|
||||||
|
owned: BTreeSet<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The call records and spend ledgers of every run in one CultCache file.
|
||||||
|
/// Records are appended and never changed; a run's sequence is dense from 1.
|
||||||
|
pub struct CallRecordStore {
|
||||||
|
state: Mutex<StoreState>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CallRecordStore {
|
||||||
|
/// Opens the file, creating it empty when absent. Every row must be a
|
||||||
|
/// canonical call record or run ledger of this schema with its key, a
|
||||||
|
/// dense sequence, and a ledger that covers its records' charges; anything
|
||||||
|
/// else, an earlier or later schema version included, is refused and
|
||||||
|
/// nothing is migrated.
|
||||||
|
pub fn open(path: impl AsRef<Path>) -> Result<Self, CallRecordError> {
|
||||||
|
let store = OwnedRedbMessagePackBackingStore::new(path.as_ref())
|
||||||
|
.map_err(|_| CallRecordError::Store)?;
|
||||||
|
store
|
||||||
|
.validate_path_identity()
|
||||||
|
.map_err(|_| CallRecordError::Store)?;
|
||||||
|
let rows = store.pull_all().map_err(|_| CallRecordError::Store)?;
|
||||||
|
let mut runs: BTreeMap<String, RunTally> = BTreeMap::new();
|
||||||
|
let mut counts: BTreeMap<String, u64> = BTreeMap::new();
|
||||||
|
let mut charged: BTreeMap<String, LaneTokens> = BTreeMap::new();
|
||||||
|
for row in &rows {
|
||||||
|
match decode_row(row)? {
|
||||||
|
DecodedRow::Call(record) => {
|
||||||
|
*counts.entry(record.run_id.clone()).or_default() += 1;
|
||||||
|
let total = charged.entry(record.run_id.clone()).or_default();
|
||||||
|
total.set(record.lane, total.of(record.lane).saturating_add(record.charged));
|
||||||
|
let tally = runs.entry(record.run_id).or_default();
|
||||||
|
tally.last_sequence = tally.last_sequence.max(record.sequence);
|
||||||
|
}
|
||||||
|
DecodedRow::Ledger(ledger) => {
|
||||||
|
let run = ledger.run_id.clone();
|
||||||
|
runs.entry(run).or_default().ledger = Some(ledger);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Sequences start at 1 and keys are unique, so a run is dense exactly
|
||||||
|
// when its rows number its highest sequence. Every record was reserved
|
||||||
|
// in a ledger before it was made, so a run with records has a ledger
|
||||||
|
// that covers what they charged.
|
||||||
|
for (run, tally) in &runs {
|
||||||
|
let rows = counts.get(run).copied().unwrap_or(0);
|
||||||
|
let recorded = charged.get(run).copied().unwrap_or_default();
|
||||||
|
let covered = tally.ledger.as_ref().is_some_and(|ledger| {
|
||||||
|
ledger.spent.wave >= recorded.wave && ledger.spent.elaboration >= recorded.elaboration
|
||||||
|
});
|
||||||
|
if rows != tally.last_sequence || !covered {
|
||||||
|
return Err(CallRecordError::Corrupt);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Self {
|
||||||
|
state: Mutex::new(StoreState {
|
||||||
|
store,
|
||||||
|
runs,
|
||||||
|
owned: BTreeSet::new(),
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lock(&self) -> Result<std::sync::MutexGuard<'_, StoreState>, CallRecordError> {
|
||||||
|
self.state.lock().map_err(|_| CallRecordError::Store)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The sequence the next record of this run must carry.
|
||||||
|
pub fn next_sequence(&self, run: &RunId) -> Result<u64, CallRecordError> {
|
||||||
|
Ok(self
|
||||||
|
.lock()?
|
||||||
|
.runs
|
||||||
|
.get(run.as_str())
|
||||||
|
.map_or(0, |tally| tally.last_sequence)
|
||||||
|
+ 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tokens this run has reserved or been charged: its persisted ledger.
|
||||||
|
pub fn spent(&self, run: &RunId) -> Result<u64, CallRecordError> {
|
||||||
|
Ok(self
|
||||||
|
.lock()?
|
||||||
|
.runs
|
||||||
|
.get(run.as_str())
|
||||||
|
.and_then(|tally| tally.ledger.as_ref())
|
||||||
|
.map_or(0, |ledger| ledger.spent.total()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What each lane of this run has reserved or been charged.
|
||||||
|
pub fn lane_spent(&self, run: &RunId) -> Result<LaneTokens, CallRecordError> {
|
||||||
|
Ok(self
|
||||||
|
.lock()?
|
||||||
|
.runs
|
||||||
|
.get(run.as_str())
|
||||||
|
.and_then(|tally| tally.ledger.as_ref())
|
||||||
|
.map_or_else(LaneTokens::default, |ledger| ledger.spent))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Takes the run's ledger for one port, or refuses when another holds it.
|
||||||
|
/// The first claim of a run writes its ledger: the cap it is opened under
|
||||||
|
/// the lane allowances, and the world it starts from. A later claim must name
|
||||||
|
/// the same cap and allowances; the start is not compared, because a resumed world has moved on.
|
||||||
|
/// With `follow`, a ledger already begun takes the cap and allowances named
|
||||||
|
/// here in place of its own, its spend kept: a caller whose limits change
|
||||||
|
/// while a run is open (the Dungeon's tuned allowances) owns them, and a
|
||||||
|
/// limit below what is already held only exhausts the lane.
|
||||||
|
fn claim(
|
||||||
|
&self,
|
||||||
|
run: &RunId,
|
||||||
|
cap: u64,
|
||||||
|
allowances: LaneTokens,
|
||||||
|
start: &RunStart,
|
||||||
|
follow: bool,
|
||||||
|
) -> Result<(), CallRecordError> {
|
||||||
|
let mut state = self.lock()?;
|
||||||
|
if !state.owned.insert(run.as_str().to_owned()) {
|
||||||
|
return Err(CallRecordError::RunInUse);
|
||||||
|
}
|
||||||
|
let begun = match state.runs.get(run.as_str()).and_then(|t| t.ledger.clone()) {
|
||||||
|
Some(ledger) if follow && (ledger.cap != cap || ledger.allowances != allowances) => {
|
||||||
|
Self::write_ledger(&mut state, RunLedger { cap, allowances, ..ledger })
|
||||||
|
}
|
||||||
|
Some(ledger) if ledger.cap != cap => Err(CallRecordError::RunMismatch(RunField::Cap)),
|
||||||
|
Some(ledger) if ledger.allowances != allowances => {
|
||||||
|
Err(CallRecordError::RunMismatch(RunField::Allowances))
|
||||||
|
}
|
||||||
|
Some(_) => Ok(()),
|
||||||
|
None => Self::write_ledger(
|
||||||
|
&mut state,
|
||||||
|
RunLedger {
|
||||||
|
run_id: run.as_str().to_owned(),
|
||||||
|
cap,
|
||||||
|
allowances,
|
||||||
|
start: start.clone(),
|
||||||
|
spent: LaneTokens::default(),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
};
|
||||||
|
if begun.is_err() {
|
||||||
|
state.owned.remove(run.as_str());
|
||||||
|
}
|
||||||
|
begun
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The world a run began from, when it has begun.
|
||||||
|
fn start_of(&self, run: &RunId) -> Result<Option<RunStart>, CallRecordError> {
|
||||||
|
Ok(self
|
||||||
|
.lock()?
|
||||||
|
.runs
|
||||||
|
.get(run.as_str())
|
||||||
|
.and_then(|tally| tally.ledger.as_ref())
|
||||||
|
.map(|ledger| ledger.start.clone()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn disown(&self, run: &RunId) {
|
||||||
|
if let Ok(mut state) = self.state.lock() {
|
||||||
|
state.owned.remove(run.as_str());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Persists the ledger, then adopts it in memory. A write that fails
|
||||||
|
/// leaves the previous ledger.
|
||||||
|
fn write_ledger(state: &mut StoreState, ledger: RunLedger) -> Result<(), CallRecordError> {
|
||||||
|
let row = CultCacheEnvelope {
|
||||||
|
key: ledger.run_id.clone(),
|
||||||
|
r#type: RUN_LEDGER_ROW.into(),
|
||||||
|
payload: rmp_serde::to_vec_named(&ledger).map_err(|_| CallRecordError::Store)?,
|
||||||
|
stored_at: Utc::now().to_rfc3339(),
|
||||||
|
schema_id: Some(RUN_LEDGER_SCHEMA.into()),
|
||||||
|
};
|
||||||
|
state.store.push(&row).map_err(|_| CallRecordError::Store)?;
|
||||||
|
let run = ledger.run_id.clone();
|
||||||
|
state.runs.entry(run).or_default().ledger = Some(ledger);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Persists `spent` as what the run's lanes hold; the run must have been
|
||||||
|
/// claimed.
|
||||||
|
fn write_spent(
|
||||||
|
state: &mut StoreState,
|
||||||
|
run: &str,
|
||||||
|
spent: LaneTokens,
|
||||||
|
) -> Result<(), CallRecordError> {
|
||||||
|
let mut ledger = state
|
||||||
|
.runs
|
||||||
|
.get(run)
|
||||||
|
.and_then(|tally| tally.ledger.clone())
|
||||||
|
.ok_or(CallRecordError::Store)?;
|
||||||
|
ledger.spent = spent;
|
||||||
|
Self::write_ledger(state, ledger)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn held(state: &StoreState, run: &RunId) -> LaneTokens {
|
||||||
|
state
|
||||||
|
.runs
|
||||||
|
.get(run.as_str())
|
||||||
|
.and_then(|tally| tally.ledger.as_ref())
|
||||||
|
.map_or_else(LaneTokens::default, |ledger| ledger.spent)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Charges `bound` to the run's persisted ledger under `lane`, or refuses
|
||||||
|
/// with `OverCap` when the run would pass `cap`, or `OverAllowance` when
|
||||||
|
/// the lane would pass its allowance. The check and the write hold one
|
||||||
|
/// lock, so calls on the wire hold their bounds.
|
||||||
|
fn reserve(
|
||||||
|
&self,
|
||||||
|
run: &RunId,
|
||||||
|
lane: Lane,
|
||||||
|
bound: u64,
|
||||||
|
cap: u64,
|
||||||
|
allowance: u64,
|
||||||
|
) -> Result<(), CallRecordError> {
|
||||||
|
let mut state = self.lock()?;
|
||||||
|
let mut held = Self::held(&state, run);
|
||||||
|
let after = held.of(lane).saturating_add(bound);
|
||||||
|
if held.total().saturating_add(bound) > cap {
|
||||||
|
return Err(CallRecordError::OverCap);
|
||||||
|
}
|
||||||
|
if after > allowance {
|
||||||
|
return Err(CallRecordError::OverAllowance);
|
||||||
|
}
|
||||||
|
held.set(lane, after);
|
||||||
|
Self::write_spent(&mut state, run.as_str(), held)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Replaces a reservation of `bound` with what the call was charged. With
|
||||||
|
/// a record, the record is stored first, so a crash between the two writes
|
||||||
|
/// leaves the larger reservation charged.
|
||||||
|
fn settle(
|
||||||
|
&self,
|
||||||
|
run: &RunId,
|
||||||
|
lane: Lane,
|
||||||
|
bound: u64,
|
||||||
|
charged: u64,
|
||||||
|
record: Option<&ProviderCallRecord>,
|
||||||
|
) -> Result<(), CallRecordError> {
|
||||||
|
let mut state = self.lock()?;
|
||||||
|
if let Some(record) = record {
|
||||||
|
Self::push_record(&mut state, record)?;
|
||||||
|
}
|
||||||
|
let mut held = Self::held(&state, run);
|
||||||
|
held.set(lane, held.of(lane).saturating_sub(bound).saturating_add(charged));
|
||||||
|
Self::write_spent(&mut state, run.as_str(), held)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn append(&self, record: &ProviderCallRecord) -> Result<(), CallRecordError> {
|
||||||
|
let mut state = self.lock()?;
|
||||||
|
Self::push_record(&mut state, record)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn push_record(
|
||||||
|
state: &mut StoreState,
|
||||||
|
record: &ProviderCallRecord,
|
||||||
|
) -> Result<(), CallRecordError> {
|
||||||
|
let last = state
|
||||||
|
.runs
|
||||||
|
.get(&record.run_id)
|
||||||
|
.map_or(0, |tally| tally.last_sequence);
|
||||||
|
if record.sequence != last + 1 {
|
||||||
|
return Err(CallRecordError::OutOfSequence);
|
||||||
|
}
|
||||||
|
let row = CultCacheEnvelope {
|
||||||
|
key: row_key(&record.run_id, record.sequence),
|
||||||
|
r#type: CALL_RECORD_ROW.into(),
|
||||||
|
payload: rmp_serde::to_vec_named(record).map_err(|_| CallRecordError::Store)?,
|
||||||
|
stored_at: Utc::now().to_rfc3339(),
|
||||||
|
schema_id: Some(CALL_RECORD_SCHEMA.into()),
|
||||||
|
};
|
||||||
|
state.store.push(&row).map_err(|_| CallRecordError::Store)?;
|
||||||
|
state
|
||||||
|
.runs
|
||||||
|
.entry(record.run_id.clone())
|
||||||
|
.or_default()
|
||||||
|
.last_sequence = record.sequence;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The run's records in sequence.
|
||||||
|
pub fn records(&self, run: &RunId) -> Result<Vec<ProviderCallRecord>, CallRecordError> {
|
||||||
|
let prefix = format!("{}/", run.as_str());
|
||||||
|
let rows = self
|
||||||
|
.lock()?
|
||||||
|
.store
|
||||||
|
.pull_all()
|
||||||
|
.map_err(|_| CallRecordError::Store)?;
|
||||||
|
let mut records = Vec::new();
|
||||||
|
for row in rows.iter().filter(|row| row.key.starts_with(&prefix)) {
|
||||||
|
if let DecodedRow::Call(record) = decode_row(row)? {
|
||||||
|
records.push(record);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
records.sort_by_key(|record| record.sequence);
|
||||||
|
Ok(records)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decorates a port for one run: reserves each call's bound in the run's
|
||||||
|
/// ledger before the provider is called, settles it to the real cost, and
|
||||||
|
/// stores every reply before returning it.
|
||||||
|
pub struct RecordingInferencePort {
|
||||||
|
inner: Arc<dyn InferencePort>,
|
||||||
|
store: Arc<CallRecordStore>,
|
||||||
|
run: RunId,
|
||||||
|
cap: u64,
|
||||||
|
allowances: LaneTokens,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RecordingInferencePort {
|
||||||
|
/// Takes ownership of the run's ledger, which resumes from the store. The
|
||||||
|
/// first open of a run records its cap, its lane allowances and the world it
|
||||||
|
/// starts from; a reopen with another cap or allowances is refused with
|
||||||
|
/// `RunMismatch`. A second
|
||||||
|
/// port on a run whose first is alive is refused with `RunInUse`.
|
||||||
|
pub fn open(
|
||||||
|
inner: Arc<dyn InferencePort>,
|
||||||
|
store: Arc<CallRecordStore>,
|
||||||
|
run: RunId,
|
||||||
|
cap_tokens: u64,
|
||||||
|
allowances: LaneTokens,
|
||||||
|
start: &RunStart,
|
||||||
|
) -> Result<Self, CallRecordError> {
|
||||||
|
store.claim(&run, cap_tokens, allowances, start, false)?;
|
||||||
|
Ok(Self { inner, store, run, cap: cap_tokens, allowances })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `open`, except that a run already begun follows the cap and allowances
|
||||||
|
/// given here instead of refusing them: its ledger takes them, the spend
|
||||||
|
/// already held stays, and a lane whose allowance now sits below its spend
|
||||||
|
/// refuses further calls as exhausted.
|
||||||
|
pub fn open_following(
|
||||||
|
inner: Arc<dyn InferencePort>,
|
||||||
|
store: Arc<CallRecordStore>,
|
||||||
|
run: RunId,
|
||||||
|
cap_tokens: u64,
|
||||||
|
allowances: LaneTokens,
|
||||||
|
start: &RunStart,
|
||||||
|
) -> Result<Self, CallRecordError> {
|
||||||
|
store.claim(&run, cap_tokens, allowances, start, true)?;
|
||||||
|
Ok(Self { inner, store, run, cap: cap_tokens, allowances })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The run this port records.
|
||||||
|
pub fn run_id(&self) -> &RunId {
|
||||||
|
&self.run
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The token cap the run was opened under.
|
||||||
|
pub fn cap(&self) -> u64 {
|
||||||
|
self.cap
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tokens reserved or charged to the run so far.
|
||||||
|
pub fn spent(&self) -> u64 {
|
||||||
|
self.store.spent(&self.run).unwrap_or(u64::MAX)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tokens reserved or charged so far, by lane.
|
||||||
|
pub fn lane_spent(&self) -> LaneTokens {
|
||||||
|
self.store.lane_spent(&self.run).unwrap_or(LaneTokens {
|
||||||
|
wave: u64::MAX,
|
||||||
|
elaboration: u64::MAX,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The run's call records in sequence.
|
||||||
|
pub fn records(&self) -> Result<Vec<ProviderCallRecord>, CallRecordError> {
|
||||||
|
self.store.records(&self.run)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The most this request can cost: its serialized bytes plus its output
|
||||||
|
/// allowance. The v4 request type cannot omit the allowance, so every
|
||||||
|
/// request has a bound.
|
||||||
|
fn bound(request: &PreparedInference) -> Result<u64, InferenceFault> {
|
||||||
|
let allowance = request.invocation.request.max_output_tokens;
|
||||||
|
let payload = serde_json::to_vec(&request.invocation.request)
|
||||||
|
.map_err(|_| InferenceFault::new("a provider request could not be measured"))?;
|
||||||
|
Ok((payload.len() as u64).saturating_add(u64::from(allowance)))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn settle(
|
||||||
|
&self,
|
||||||
|
lane: Lane,
|
||||||
|
bound: u64,
|
||||||
|
identity: Identity,
|
||||||
|
result: Result<InferenceOutput, InferenceFault>,
|
||||||
|
) -> Result<InferenceOutput, InferenceFault> {
|
||||||
|
// A fault leaves its reservation charged: the request may have run.
|
||||||
|
let output = result?;
|
||||||
|
let charged = match output.usage {
|
||||||
|
Some(usage) => usage.prompt.saturating_add(usage.completion),
|
||||||
|
None => bound,
|
||||||
|
};
|
||||||
|
if charged > bound {
|
||||||
|
self.store
|
||||||
|
.settle(&self.run, lane, bound, charged, None)
|
||||||
|
.map_err(unrecorded)?;
|
||||||
|
return Err(InferenceFault::budget_exhausted());
|
||||||
|
}
|
||||||
|
let Identity {
|
||||||
|
purpose,
|
||||||
|
model,
|
||||||
|
content_sha256,
|
||||||
|
request_id,
|
||||||
|
} = identity;
|
||||||
|
let record = ProviderCallRecord {
|
||||||
|
run_id: self.run.as_str().to_owned(),
|
||||||
|
sequence: self.store.next_sequence(&self.run).map_err(unrecorded)?,
|
||||||
|
purpose,
|
||||||
|
lane,
|
||||||
|
request_id,
|
||||||
|
model,
|
||||||
|
content_sha256,
|
||||||
|
events: output.events.clone(),
|
||||||
|
receipt_digest: output.receipt_digest.clone(),
|
||||||
|
usage: output.usage,
|
||||||
|
charged,
|
||||||
|
};
|
||||||
|
self.store
|
||||||
|
.settle(&self.run, lane, bound, charged, Some(&record))
|
||||||
|
.map_err(unrecorded)?;
|
||||||
|
Ok(output)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a call is recorded as, known before the provider is called.
|
||||||
|
struct Identity {
|
||||||
|
purpose: InferencePurpose,
|
||||||
|
model: String,
|
||||||
|
content_sha256: String,
|
||||||
|
request_id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for RecordingInferencePort {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.store.disown(&self.run);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn unrecorded(_: CallRecordError) -> InferenceFault {
|
||||||
|
InferenceFault::integrity_violation("a provider call could not be recorded")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl InferencePort for RecordingInferencePort {
|
||||||
|
fn prepare(&self, request: InferenceRequest) -> Result<PreparedInference, InferenceFault> {
|
||||||
|
self.inner.prepare(request)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn infer(&self, request: PreparedInference) -> Result<InferenceOutput, InferenceFault> {
|
||||||
|
let bound = Self::bound(&request)?;
|
||||||
|
// The room lane is no window's: a play call that reached this port
|
||||||
|
// would spend background budget.
|
||||||
|
let Some(lane) = Lane::of(request.purpose) else {
|
||||||
|
return Err(InferenceFault::integrity_violation(
|
||||||
|
"the room lane is not metered by a background window",
|
||||||
|
));
|
||||||
|
};
|
||||||
|
let identity = Identity {
|
||||||
|
purpose: request.purpose,
|
||||||
|
model: request.invocation.request.model.clone(),
|
||||||
|
content_sha256: content_digest(&request.invocation.request)?,
|
||||||
|
request_id: request.invocation.request.request_id.clone(),
|
||||||
|
};
|
||||||
|
self.store
|
||||||
|
.reserve(&self.run, lane, bound, self.cap, self.allowances.of(lane))
|
||||||
|
.map_err(|error| match error {
|
||||||
|
CallRecordError::OverCap | CallRecordError::OverAllowance => {
|
||||||
|
InferenceFault::budget_exhausted()
|
||||||
|
}
|
||||||
|
_ => unrecorded(error),
|
||||||
|
})?;
|
||||||
|
let result = self.inner.infer(request).await;
|
||||||
|
self.settle(lane, bound, identity, result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the calls of one wave cost, by lane and by node. The port never learns
|
||||||
|
/// which node a call served: a record's request id begins with the command id
|
||||||
|
/// it ran under, and the frozen wave names the command ids of each node's
|
||||||
|
/// cells, so attribution is this join and nothing the port keeps. Only settled
|
||||||
|
/// calls have records; a call that faulted left its reservation in the ledger
|
||||||
|
/// and no record here.
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||||
|
pub struct WaveSpend {
|
||||||
|
/// Tokens charged by the wave's joined calls, by lane.
|
||||||
|
pub lanes: LaneTokens,
|
||||||
|
/// Per node, in the order the frozen cells first name them. A node whose
|
||||||
|
/// cells made no recorded call is listed with zero.
|
||||||
|
pub nodes: Vec<NodeSpend>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One node's settled calls in a wave.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct NodeSpend {
|
||||||
|
pub node: NodeId,
|
||||||
|
/// The node's hierarchy distance from the focus when it was planned.
|
||||||
|
pub distance: u8,
|
||||||
|
pub calls: u32,
|
||||||
|
pub charged: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WaveSpend {
|
||||||
|
/// The records of wave `ordinal` of `world`: every record whose request id
|
||||||
|
/// begins with a command id of one of `frozen`'s cells. Records of other
|
||||||
|
/// waves or lanes are not this wave's and are left out.
|
||||||
|
pub fn of(
|
||||||
|
records: &[ProviderCallRecord],
|
||||||
|
world: WorldId,
|
||||||
|
ordinal: TickIndex,
|
||||||
|
frozen: &[FrozenCell],
|
||||||
|
) -> Result<Self, ControllerError> {
|
||||||
|
let mut spend = Self::default();
|
||||||
|
let mut prefixes: Vec<(String, usize)> = Vec::new();
|
||||||
|
for cell in frozen {
|
||||||
|
let at = match spend.nodes.iter().position(|node| node.node == cell.node) {
|
||||||
|
Some(at) => at,
|
||||||
|
None => {
|
||||||
|
spend.nodes.push(NodeSpend {
|
||||||
|
node: cell.node,
|
||||||
|
distance: cell.distance,
|
||||||
|
calls: 0,
|
||||||
|
charged: 0,
|
||||||
|
});
|
||||||
|
spend.nodes.len() - 1
|
||||||
|
}
|
||||||
|
};
|
||||||
|
for command in cell.command_ids(world, ordinal) {
|
||||||
|
prefixes.push((request_id_prefix(command)?, at));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for record in records {
|
||||||
|
let Some(&(_, at)) = prefixes
|
||||||
|
.iter()
|
||||||
|
.find(|(prefix, _)| record.request_id.starts_with(prefix))
|
||||||
|
else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let node = &mut spend.nodes[at];
|
||||||
|
node.calls += 1;
|
||||||
|
node.charged = node.charged.saturating_add(record.charged);
|
||||||
|
let lane = spend.lanes.of(record.lane).saturating_add(record.charged);
|
||||||
|
spend.lanes.set(record.lane, lane);
|
||||||
|
}
|
||||||
|
Ok(spend)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Serves a run's stored replies, in sequence, to the same requests, matched
|
||||||
|
/// by what they ask of the provider and not by the ids that name them. It holds
|
||||||
|
/// no provider and makes no call: a request that is not the next recorded one
|
||||||
|
/// is a fault.
|
||||||
|
pub struct ReplayInferencePort {
|
||||||
|
caller_runtime_id: String,
|
||||||
|
pending: Mutex<VecDeque<ProviderCallRecord>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ReplayInferencePort {
|
||||||
|
/// Replays `run` from the store against `world`, a restored copy of the
|
||||||
|
/// world the run started from. Any other world is refused here, before a
|
||||||
|
/// call, with `RunMismatch` naming the field; a run the store never began
|
||||||
|
/// is `NotReplayable`.
|
||||||
|
pub fn new(
|
||||||
|
caller_runtime_id: impl Into<String>,
|
||||||
|
store: &CallRecordStore,
|
||||||
|
run: &RunId,
|
||||||
|
world: &RunStart,
|
||||||
|
) -> Result<Self, CallRecordError> {
|
||||||
|
let began = store.start_of(run)?.ok_or(CallRecordError::NotReplayable)?;
|
||||||
|
if began.world_id != world.world_id {
|
||||||
|
return Err(CallRecordError::RunMismatch(RunField::WorldId));
|
||||||
|
}
|
||||||
|
if began.state_digest != world.state_digest {
|
||||||
|
return Err(CallRecordError::RunMismatch(RunField::StateDigest));
|
||||||
|
}
|
||||||
|
Ok(Self {
|
||||||
|
caller_runtime_id: caller_runtime_id.into(),
|
||||||
|
pending: Mutex::new(store.records(run)?.into()),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl InferencePort for ReplayInferencePort {
|
||||||
|
fn prepare(&self, request: InferenceRequest) -> Result<PreparedInference, InferenceFault> {
|
||||||
|
PreparedInference::prepare(
|
||||||
|
&self.caller_runtime_id,
|
||||||
|
unix_ms()?.saturating_add(REQUEST_EXPIRY.as_millis() as u64),
|
||||||
|
request,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn infer(&self, request: PreparedInference) -> Result<InferenceOutput, InferenceFault> {
|
||||||
|
let mut pending = self
|
||||||
|
.pending
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| InferenceFault::integrity_violation("the replay queue was poisoned"))?;
|
||||||
|
let digest = content_digest(&request.invocation.request)?;
|
||||||
|
let Some(next) = pending.front() else {
|
||||||
|
return Err(InferenceFault::integrity_violation(
|
||||||
|
"replay has no recorded call left",
|
||||||
|
));
|
||||||
|
};
|
||||||
|
if next.content_sha256 != digest {
|
||||||
|
return Err(InferenceFault::integrity_violation(
|
||||||
|
"the request is not the next recorded call",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let output = next.output();
|
||||||
|
pending.pop_front();
|
||||||
|
Ok(output)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests;
|
||||||
1437
crates/ghostlight/src/verse/calls/tests.rs
Normal file
1437
crates/ghostlight/src/verse/calls/tests.rs
Normal file
File diff suppressed because it is too large
Load diff
144
crates/ghostlight/src/verse/genesis.rs
Normal file
144
crates/ghostlight/src/verse/genesis.rs
Normal file
|
|
@ -0,0 +1,144 @@
|
||||||
|
//! The canonical Aetheria verse world's genesis.
|
||||||
|
//!
|
||||||
|
//! One intent lowers to one `CreateWorld`: a commons, every grammar verb
|
||||||
|
//! declared as an affordance, and each Aetheria faction as an institution
|
||||||
|
//! imported by its record key. The world is bound to the catalog's grammar, so
|
||||||
|
//! the kernel refuses any affordance the grammar does not carry.
|
||||||
|
//!
|
||||||
|
//! Phase A verbs record the act and change no component: an outcome band with
|
||||||
|
//! no effects, and the act carried as the utterance that makes an entry
|
||||||
|
//! admissible. Ghostlight owns each verb's lowering to kernel effects (ruling
|
||||||
|
//! `verb-effects-ghostlight`), and those arrive with phase B.
|
||||||
|
|
||||||
|
use crate::aetheria::AetheriaCatalog;
|
||||||
|
use crate::mailbox::{MailboxError, commons_declaration, commons_ref};
|
||||||
|
use crate::patch::{
|
||||||
|
AffordanceDeclaration, AffordanceKindName, AudienceSpec, Declaration, DraftHandle, EvidenceRef,
|
||||||
|
FactDeclaration, FactStandingRef, OutcomeBand, Precondition, Ref, Statement, SubjectDeclaration,
|
||||||
|
kernel_speak_entry, kernel_speak_grant,
|
||||||
|
};
|
||||||
|
use crate::{
|
||||||
|
CommandId, CreateWorld, LensWeights, NewController, PrincipalId, SubjectKind,
|
||||||
|
WorldPatch, WorldScaleIntentRef,
|
||||||
|
};
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
const COMMIT_LEN: usize = 40;
|
||||||
|
|
||||||
|
/// What a caller states to create the canonical verse world. Everything else a
|
||||||
|
/// world needs (the commons, the subjects, the affordances, their grants and
|
||||||
|
/// the provenance of what is known) is derived from the catalog.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct CreateVerseWorldIntent {
|
||||||
|
pub id: CommandId,
|
||||||
|
pub title: String,
|
||||||
|
pub brief: String,
|
||||||
|
pub catalog: AetheriaCatalog,
|
||||||
|
/// The Aetheria commit the catalog was read at: 40 lower-case hex digits.
|
||||||
|
/// It is the provenance of every fact the world holds about a faction.
|
||||||
|
pub aetheria_commit: String,
|
||||||
|
pub lens_weights: LensWeights,
|
||||||
|
pub targets: BTreeMap<SubjectKind, u32>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum VerseGenesisError {
|
||||||
|
#[error("aetheria_commit is not 40 lower-case hex digits")]
|
||||||
|
NotACommit,
|
||||||
|
#[error(transparent)]
|
||||||
|
Mailbox(#[from] MailboxError),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CreateVerseWorldIntent {
|
||||||
|
/// The one lowering. The kernel supplies the `speak` entry at genesis and
|
||||||
|
/// holds it to the grammar, so it is granted here and never declared.
|
||||||
|
pub(crate) fn lower(self, owner: PrincipalId) -> Result<CreateWorld, VerseGenesisError> {
|
||||||
|
let commit = &self.aetheria_commit;
|
||||||
|
if commit.len() != COMMIT_LEN
|
||||||
|
|| !commit
|
||||||
|
.bytes()
|
||||||
|
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
|
||||||
|
{
|
||||||
|
return Err(VerseGenesisError::NotACommit);
|
||||||
|
}
|
||||||
|
|
||||||
|
let speak = kernel_speak_entry().kind;
|
||||||
|
let mut grants = kernel_speak_grant();
|
||||||
|
let mut declarations = vec![commons_declaration()];
|
||||||
|
for (kind, verb) in self.catalog.grammar.verbs() {
|
||||||
|
if kind == speak.0 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let handle = DraftHandle::new(format!("verb-{kind}"));
|
||||||
|
grants.insert(Ref::Draft(handle.clone()));
|
||||||
|
declarations.push(Declaration::Affordance(AffordanceDeclaration {
|
||||||
|
handle,
|
||||||
|
kind: AffordanceKindName(kind.to_owned()),
|
||||||
|
roles: verb.role_specs(),
|
||||||
|
preconditions: vec![Precondition::CanBroadcast {
|
||||||
|
via: AudienceSpec::Colocated,
|
||||||
|
}],
|
||||||
|
effect_slots: Vec::new(),
|
||||||
|
outcome_bands: vec![OutcomeBand {
|
||||||
|
weight: 1,
|
||||||
|
effects: Vec::new(),
|
||||||
|
}],
|
||||||
|
// The kernel refuses an entry that can neither change a
|
||||||
|
// component nor speak, and a speaking entry needs an audience,
|
||||||
|
// so a phase A verb is its own utterance to the room: the act
|
||||||
|
// is recorded as speech and nothing else changes.
|
||||||
|
carries_speech: true,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut evidence = Vec::new();
|
||||||
|
for (position, faction) in self.catalog.factions.iter().enumerate() {
|
||||||
|
declarations.push(Declaration::Subject(SubjectDeclaration {
|
||||||
|
handle: DraftHandle::new(format!("faction-{position}")),
|
||||||
|
label: faction.name.trim().to_owned(),
|
||||||
|
kind: SubjectKind::Institution,
|
||||||
|
controller: NewController::OperationalAgent,
|
||||||
|
affordances: grants.clone(),
|
||||||
|
position: Some(commons_ref()),
|
||||||
|
import_key: Some(faction.key.clone()),
|
||||||
|
}));
|
||||||
|
// A faction with no description has nothing to state.
|
||||||
|
if let Some(statement) = Statement::new(faction.description.trim()) {
|
||||||
|
let receipt = EvidenceRef::new(format!(
|
||||||
|
"aetheria:{commit}:{}/{}",
|
||||||
|
faction.key.schema(),
|
||||||
|
faction.key.record()
|
||||||
|
));
|
||||||
|
evidence.push(receipt.clone());
|
||||||
|
declarations.push(Declaration::Fact(FactDeclaration {
|
||||||
|
handle: DraftHandle::new(format!("fact-{position}")),
|
||||||
|
label: faction.name.trim().to_owned(),
|
||||||
|
statement,
|
||||||
|
standing: FactStandingRef::Canonical { evidence: receipt },
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(CreateWorld {
|
||||||
|
id: self.id,
|
||||||
|
owner,
|
||||||
|
title: self.title,
|
||||||
|
brief: self.brief,
|
||||||
|
patch: WorldPatch {
|
||||||
|
declarations,
|
||||||
|
operations: Vec::new(),
|
||||||
|
evidence,
|
||||||
|
},
|
||||||
|
scale_intent: WorldScaleIntentRef {
|
||||||
|
targets: self.targets,
|
||||||
|
jurisdictions: BTreeMap::new(),
|
||||||
|
},
|
||||||
|
lens_weights: self.lens_weights,
|
||||||
|
grammar: Some(self.catalog.grammar),
|
||||||
|
era: None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests;
|
||||||
477
crates/ghostlight/src/verse/genesis/tests.rs
Normal file
477
crates/ghostlight/src/verse/genesis/tests.rs
Normal file
|
|
@ -0,0 +1,477 @@
|
||||||
|
use super::*;
|
||||||
|
use crate::aetheria::read_aetheria_catalog;
|
||||||
|
use crate::patch::{FactStanding, Mismatch};
|
||||||
|
use crate::tests::{auth_principal, owner, stock_weights};
|
||||||
|
use crate::{
|
||||||
|
CommandBody, ControllerMode, GrammarBinding, GrammarReferentKind, GrammarRole, GrammarVerb,
|
||||||
|
KernelError, PrincipalCommandIntent, RenderPath, VerifiedPrincipalEvidence, WorldKernel,
|
||||||
|
WorldMailbox, WorldPhase,
|
||||||
|
};
|
||||||
|
use chrono::{Duration, Utc};
|
||||||
|
use std::collections::BTreeSet;
|
||||||
|
|
||||||
|
/// Aetheria master when the fixture catalog was written.
|
||||||
|
const COMMIT: &str = "92b82e9aa5bb422c568c4bfc85a8f641426a41fc";
|
||||||
|
const OTHER_COMMIT: &str = "0123456789abcdef0123456789abcdef01234567";
|
||||||
|
|
||||||
|
const FIXTURE: &str = concat!(
|
||||||
|
env!("CARGO_MANIFEST_DIR"),
|
||||||
|
"/tests/fixtures/aetheria-verse-catalog.cc"
|
||||||
|
);
|
||||||
|
|
||||||
|
fn catalog() -> AetheriaCatalog {
|
||||||
|
read_aetheria_catalog(FIXTURE).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn intent_of(catalog: AetheriaCatalog, commit: &str) -> CreateVerseWorldIntent {
|
||||||
|
CreateVerseWorldIntent {
|
||||||
|
id: CommandId::new(),
|
||||||
|
title: "The Verse".into(),
|
||||||
|
brief: "Aetheria.".into(),
|
||||||
|
catalog,
|
||||||
|
aetheria_commit: commit.into(),
|
||||||
|
lens_weights: stock_weights(),
|
||||||
|
targets: BTreeMap::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A world created through the kernel from the lowering, for what the
|
||||||
|
/// snapshot hides: the facts' evidence.
|
||||||
|
fn kernel_of(intent: CreateVerseWorldIntent) -> (tempfile::TempDir, Result<WorldKernel, KernelError>) {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let world = intent.lower(owner()).unwrap();
|
||||||
|
let result = WorldKernel::create(dir.path().join("world.cc"), world, &auth_principal(owner()))
|
||||||
|
.map(|(kernel, _)| kernel);
|
||||||
|
(dir, result)
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Verse {
|
||||||
|
_dir: tempfile::TempDir,
|
||||||
|
_task: tokio::task::JoinHandle<()>,
|
||||||
|
mailbox: WorldMailbox,
|
||||||
|
principal: VerifiedPrincipalEvidence,
|
||||||
|
receipt: crate::CreationReceipt,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn verse(intent: CreateVerseWorldIntent) -> Verse {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let (mailbox, task) = WorldMailbox::open(dir.path().join("world.cc")).unwrap();
|
||||||
|
let principal =
|
||||||
|
VerifiedPrincipalEvidence::fixture("verse-owner", Utc::now() + Duration::hours(1));
|
||||||
|
let receipt = mailbox.create_verse(intent, &principal).await.unwrap();
|
||||||
|
Verse {
|
||||||
|
_dir: dir,
|
||||||
|
_task: task,
|
||||||
|
mailbox,
|
||||||
|
principal,
|
||||||
|
receipt,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn verse_genesis_from_the_aetheria_fixture() {
|
||||||
|
let catalog = catalog();
|
||||||
|
let verse = verse(intent_of(catalog.clone(), COMMIT)).await;
|
||||||
|
let snapshot = verse.mailbox.snapshot().await.unwrap();
|
||||||
|
|
||||||
|
// One institution per faction, keyed by its record, named by its Name.
|
||||||
|
let mut factions: Vec<_> = snapshot
|
||||||
|
.subjects
|
||||||
|
.iter()
|
||||||
|
.map(|subject| {
|
||||||
|
(
|
||||||
|
subject.import_key.clone().unwrap(),
|
||||||
|
subject.label.clone(),
|
||||||
|
subject.kind,
|
||||||
|
subject.controller_mode,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
factions.sort_by(|a, b| a.0.cmp(&b.0));
|
||||||
|
let expected: Vec<_> = catalog
|
||||||
|
.factions
|
||||||
|
.iter()
|
||||||
|
.map(|faction| {
|
||||||
|
(
|
||||||
|
faction.key.clone(),
|
||||||
|
faction.name.clone(),
|
||||||
|
SubjectKind::Institution,
|
||||||
|
Some(ControllerMode::OperationalAgent),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
assert_eq!(factions.len(), 2);
|
||||||
|
assert_eq!(factions, expected);
|
||||||
|
|
||||||
|
// One fact per faction, carrying its description.
|
||||||
|
let statements: BTreeSet<_> = snapshot
|
||||||
|
.facts
|
||||||
|
.iter()
|
||||||
|
.map(|fact| fact.statement.as_str().to_owned())
|
||||||
|
.collect();
|
||||||
|
assert_eq!(
|
||||||
|
statements,
|
||||||
|
catalog
|
||||||
|
.factions
|
||||||
|
.iter()
|
||||||
|
.map(|faction| faction.description.clone())
|
||||||
|
.collect::<BTreeSet<_>>()
|
||||||
|
);
|
||||||
|
|
||||||
|
// The world is bound to the catalog's grammar.
|
||||||
|
assert_eq!(snapshot.grammar, Some(catalog.grammar.identity()));
|
||||||
|
assert_eq!(verse.receipt.world_id, snapshot.world_id);
|
||||||
|
|
||||||
|
// Every faction stands in the one commons.
|
||||||
|
let commons: Vec<_> = snapshot
|
||||||
|
.places
|
||||||
|
.iter()
|
||||||
|
.filter(|place| place.label == "The Commons")
|
||||||
|
.collect();
|
||||||
|
assert_eq!(commons.len(), 1);
|
||||||
|
assert!(
|
||||||
|
snapshot
|
||||||
|
.subjects
|
||||||
|
.iter()
|
||||||
|
.all(|subject| subject.position == Some(commons[0].id))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn each_fact_cites_its_faction_record_and_the_commit_it_was_read_at() {
|
||||||
|
for commit in [COMMIT, OTHER_COMMIT] {
|
||||||
|
let (_dir, kernel) = kernel_of(intent_of(catalog(), commit));
|
||||||
|
let kernel = kernel.unwrap();
|
||||||
|
let evidence: BTreeSet<String> = kernel
|
||||||
|
.state
|
||||||
|
.facts
|
||||||
|
.values()
|
||||||
|
.map(|fact| match &fact.standing {
|
||||||
|
FactStanding::Canonical { evidence } => evidence.text().to_owned(),
|
||||||
|
other => panic!("a verse fact is canonical, not {other:?}"),
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
assert_eq!(
|
||||||
|
evidence,
|
||||||
|
catalog()
|
||||||
|
.factions
|
||||||
|
.iter()
|
||||||
|
.map(|faction| format!(
|
||||||
|
"aetheria:{commit}:aetheria.faction/{}",
|
||||||
|
faction.key.record()
|
||||||
|
))
|
||||||
|
.collect::<BTreeSet<_>>()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_commit_is_forty_lower_case_hex_digits() {
|
||||||
|
for bad in [
|
||||||
|
"",
|
||||||
|
&COMMIT[..39],
|
||||||
|
&format!("{COMMIT}0"),
|
||||||
|
&COMMIT.to_uppercase(),
|
||||||
|
&format!("{}g", &COMMIT[..39]),
|
||||||
|
] {
|
||||||
|
assert!(
|
||||||
|
matches!(
|
||||||
|
intent_of(catalog(), bad).lower(owner()),
|
||||||
|
Err(VerseGenesisError::NotACommit)
|
||||||
|
),
|
||||||
|
"{bad:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert!(intent_of(catalog(), COMMIT).lower(owner()).is_ok());
|
||||||
|
assert!(!VerseGenesisError::NotACommit.to_string().contains(COMMIT));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn verse_genesis_refuses_a_duplicate_faction_record() {
|
||||||
|
let mut twice = catalog();
|
||||||
|
let first = twice.factions[0].clone();
|
||||||
|
twice.factions.push(first);
|
||||||
|
// The lowering does not decide: it declares all three.
|
||||||
|
let world = intent_of(twice.clone(), COMMIT).lower(owner()).unwrap();
|
||||||
|
let subjects = world
|
||||||
|
.patch
|
||||||
|
.declarations
|
||||||
|
.iter()
|
||||||
|
.filter(|declaration| matches!(declaration, Declaration::Subject(_)))
|
||||||
|
.count();
|
||||||
|
assert_eq!(subjects, 3);
|
||||||
|
|
||||||
|
let (_dir, kernel) = kernel_of(intent_of(twice, COMMIT));
|
||||||
|
let Err(KernelError::PatchRejected(set)) = kernel else {
|
||||||
|
panic!("a second faction under one record key was admitted");
|
||||||
|
};
|
||||||
|
assert!(
|
||||||
|
set.iter()
|
||||||
|
.any(|mismatch| matches!(mismatch, Mismatch::DuplicateImportKey { .. })),
|
||||||
|
"{set:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn every_granted_affordance_is_a_grammar_verb() {
|
||||||
|
let catalog = catalog();
|
||||||
|
let verse = verse(intent_of(catalog.clone(), COMMIT)).await;
|
||||||
|
let snapshot = verse.mailbox.snapshot().await.unwrap();
|
||||||
|
|
||||||
|
let mut kinds: Vec<_> = snapshot
|
||||||
|
.affordances
|
||||||
|
.iter()
|
||||||
|
.map(|affordance| affordance.entry.kind.0.clone())
|
||||||
|
.collect();
|
||||||
|
kinds.sort();
|
||||||
|
// Each verb once: the kernel's speak is the grammar's speak.
|
||||||
|
assert_eq!(
|
||||||
|
kinds,
|
||||||
|
catalog
|
||||||
|
.grammar
|
||||||
|
.verbs()
|
||||||
|
.map(|(kind, _)| kind.to_owned())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
);
|
||||||
|
assert!(kinds.contains(&"speak".to_owned()));
|
||||||
|
|
||||||
|
// Each has its render path from the grammar, and phase A changes nothing.
|
||||||
|
for affordance in &snapshot.affordances {
|
||||||
|
let verb = catalog.grammar.verb(&affordance.entry.kind.0).unwrap();
|
||||||
|
assert_eq!(affordance.render_path, Some(verb.render_path));
|
||||||
|
assert!(affordance.entry.effect_slots.is_empty());
|
||||||
|
assert_eq!(affordance.entry.outcome_bands.len(), 1);
|
||||||
|
assert!(affordance.entry.outcome_bands[0].effects.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Every faction is granted every verb.
|
||||||
|
let all: BTreeSet<_> = snapshot.affordances.iter().map(|a| a.id).collect();
|
||||||
|
for subject in &snapshot.subjects {
|
||||||
|
assert_eq!(subject.affordances, all);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn factions_get_opportunities() {
|
||||||
|
let verse = verse(intent_of(catalog(), COMMIT)).await;
|
||||||
|
for body in [CommandBody::ApproveDraft, CommandBody::ActivateWorld] {
|
||||||
|
let revision = verse.mailbox.snapshot().await.unwrap().revision;
|
||||||
|
verse
|
||||||
|
.mailbox
|
||||||
|
.submit_principal(
|
||||||
|
PrincipalCommandIntent {
|
||||||
|
id: CommandId::new(),
|
||||||
|
world_id: verse.receipt.world_id,
|
||||||
|
expected_revision: revision,
|
||||||
|
body,
|
||||||
|
},
|
||||||
|
&verse.principal,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
let snapshot = verse.mailbox.snapshot().await.unwrap();
|
||||||
|
assert_eq!(snapshot.phase, WorldPhase::Active);
|
||||||
|
assert_eq!(snapshot.opportunities.len(), catalog().factions.len());
|
||||||
|
let scopes: BTreeSet<_> = snapshot.opportunities.iter().map(|o| o.scope).collect();
|
||||||
|
assert_eq!(scopes.len(), snapshot.opportunities.len());
|
||||||
|
for opportunity in &snapshot.opportunities {
|
||||||
|
assert_eq!(opportunity.controller_mode, ControllerMode::OperationalAgent);
|
||||||
|
assert_eq!(opportunity.affordance_ids.len(), snapshot.affordances.len());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_faction_without_a_description_holds_no_fact() {
|
||||||
|
let mut bare = catalog();
|
||||||
|
bare.factions[0].description = " ".into();
|
||||||
|
bare.factions[1].description = " Second. ".into();
|
||||||
|
let (_dir, kernel) = kernel_of(intent_of(bare, COMMIT));
|
||||||
|
let facts: Vec<_> = kernel
|
||||||
|
.unwrap()
|
||||||
|
.state
|
||||||
|
.facts
|
||||||
|
.values()
|
||||||
|
.map(|fact| fact.statement.as_str().to_owned())
|
||||||
|
.collect();
|
||||||
|
assert_eq!(facts, vec!["Second.".to_owned()]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_grammar_the_kernel_speak_cannot_live_in_refuses_genesis() {
|
||||||
|
let mut mute = catalog();
|
||||||
|
mute.grammar = GrammarBinding::new(
|
||||||
|
"aetheria.verse_grammar",
|
||||||
|
1,
|
||||||
|
[(
|
||||||
|
"haul".to_owned(),
|
||||||
|
GrammarVerb {
|
||||||
|
render_path: RenderPath::ShipAction,
|
||||||
|
roles: vec![GrammarRole {
|
||||||
|
role: "cargo".into(),
|
||||||
|
referent: GrammarReferentKind::Cargo,
|
||||||
|
}],
|
||||||
|
},
|
||||||
|
)],
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let (_dir, kernel) = kernel_of(intent_of(mute, COMMIT));
|
||||||
|
let Err(KernelError::PatchRejected(set)) = kernel else {
|
||||||
|
panic!("a world whose grammar has no speak was admitted");
|
||||||
|
};
|
||||||
|
assert!(
|
||||||
|
set.iter()
|
||||||
|
.any(|mismatch| matches!(mismatch, Mismatch::AffordanceKindNotInGrammar { .. })),
|
||||||
|
"{set:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn the_dungeon_ingress_still_creates_an_unbound_world() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let (mailbox, _task) = WorldMailbox::open(dir.path().join("world.cc")).unwrap();
|
||||||
|
let principal =
|
||||||
|
VerifiedPrincipalEvidence::fixture("dungeon-owner", Utc::now() + Duration::hours(1));
|
||||||
|
mailbox
|
||||||
|
.create(
|
||||||
|
crate::CreateWorldIntent {
|
||||||
|
id: CommandId::new(),
|
||||||
|
title: "Dungeon".into(),
|
||||||
|
brief: String::new(),
|
||||||
|
human_subject_label: "Player".into(),
|
||||||
|
narrative_persona_label: None,
|
||||||
|
operational_agent_label: None,
|
||||||
|
targets: BTreeMap::new(),
|
||||||
|
jurisdictions: Vec::new(),
|
||||||
|
lens_weights: stock_weights(),
|
||||||
|
era: None,
|
||||||
|
},
|
||||||
|
&principal,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let snapshot = mailbox.snapshot().await.unwrap();
|
||||||
|
assert_eq!(snapshot.grammar, None);
|
||||||
|
assert!(
|
||||||
|
snapshot
|
||||||
|
.places
|
||||||
|
.iter()
|
||||||
|
.any(|place| place.label == "The Commons")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_faction_name_is_trimmed_into_its_institution_label() {
|
||||||
|
let mut padded = catalog();
|
||||||
|
let expected = padded.factions[0].name.trim().to_owned();
|
||||||
|
padded.factions[0].name = format!(" {expected}\t ");
|
||||||
|
let key = padded.factions[0].key.clone();
|
||||||
|
let verse = verse(intent_of(padded, COMMIT)).await;
|
||||||
|
let snapshot = verse.mailbox.snapshot().await.unwrap();
|
||||||
|
let subject = snapshot
|
||||||
|
.subjects
|
||||||
|
.iter()
|
||||||
|
.find(|subject| subject.import_key.as_ref() == Some(&key))
|
||||||
|
.expect("the padded faction was created");
|
||||||
|
assert_eq!(subject.label, expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn genesis_twice_with_one_intent_is_one_creation() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let (mailbox, _task) = WorldMailbox::open(dir.path().join("world.cc")).unwrap();
|
||||||
|
let principal =
|
||||||
|
VerifiedPrincipalEvidence::fixture("verse-owner", Utc::now() + Duration::hours(1));
|
||||||
|
let intent = intent_of(catalog(), COMMIT);
|
||||||
|
let first = mailbox.create_verse(intent.clone(), &principal).await.unwrap();
|
||||||
|
let before = mailbox.snapshot().await.unwrap();
|
||||||
|
let again = mailbox.create_verse(intent, &principal).await.unwrap();
|
||||||
|
let after = mailbox.snapshot().await.unwrap();
|
||||||
|
assert_eq!(again, first);
|
||||||
|
assert_eq!(after.revision, before.revision);
|
||||||
|
assert_eq!(after.state_digest, before.state_digest);
|
||||||
|
assert_eq!(after.subjects.len(), before.subjects.len());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn genesis_under_another_command_id_finds_the_world_occupied() {
|
||||||
|
let verse = verse(intent_of(catalog(), COMMIT)).await;
|
||||||
|
let before = verse.mailbox.snapshot().await.unwrap();
|
||||||
|
let refused = verse
|
||||||
|
.mailbox
|
||||||
|
.create_verse(intent_of(catalog(), COMMIT), &verse.principal)
|
||||||
|
.await;
|
||||||
|
assert!(
|
||||||
|
matches!(
|
||||||
|
refused,
|
||||||
|
Err(VerseGenesisError::Mailbox(MailboxError::Kernel(
|
||||||
|
KernelError::CreationTargetOccupied
|
||||||
|
)))
|
||||||
|
),
|
||||||
|
"{refused:?}"
|
||||||
|
);
|
||||||
|
let after = verse.mailbox.snapshot().await.unwrap();
|
||||||
|
assert_eq!(after.revision, before.revision);
|
||||||
|
assert_eq!(after.state_digest, before.state_digest);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pins the standing phase A behaviour (ruling `ship-acts-speech-shaped-phase-a`):
|
||||||
|
/// the lowering admits a ship verb only as an utterance,
|
||||||
|
/// and committing it asserts a claim fact the room hears.
|
||||||
|
#[test]
|
||||||
|
fn phase_a_ship_verbs_are_spoken_acts_in_the_room() {
|
||||||
|
use crate::tests::{command, opportunity_for, spoken, submit_owner};
|
||||||
|
use crate::{
|
||||||
|
AuthenticatedCaller, CallerId, DecisionInvocation, Role, RoleBinding, SubmitReceipt,
|
||||||
|
Target,
|
||||||
|
};
|
||||||
|
|
||||||
|
let (_scratch, kernel) = kernel_of(intent_of(catalog(), COMMIT));
|
||||||
|
let mut kernel = kernel.unwrap();
|
||||||
|
for body in [CommandBody::ApproveDraft, CommandBody::ActivateWorld] {
|
||||||
|
let snapshot = kernel.snapshot().unwrap();
|
||||||
|
submit_owner(&mut kernel, &snapshot, body);
|
||||||
|
}
|
||||||
|
let active = kernel.snapshot().unwrap();
|
||||||
|
let attack = active
|
||||||
|
.affordances
|
||||||
|
.iter()
|
||||||
|
.find(|a| a.entry.kind.0 == "attack")
|
||||||
|
.unwrap()
|
||||||
|
.id;
|
||||||
|
let [first, second] = [&active.subjects[0], &active.subjects[1]];
|
||||||
|
let opportunity = opportunity_for(&active, first.id);
|
||||||
|
let caller = CallerId::Controller(opportunity.controller_id);
|
||||||
|
let invocation = |speech: Option<&str>| DecisionInvocation {
|
||||||
|
affordance: attack,
|
||||||
|
bindings: vec![RoleBinding {
|
||||||
|
role: Role("target".into()),
|
||||||
|
target: Target::Subject(second.id),
|
||||||
|
}],
|
||||||
|
proposed: Vec::new(),
|
||||||
|
speech: speech.map(|text| crate::patch::Statement::new(text).unwrap()),
|
||||||
|
display: None,
|
||||||
|
};
|
||||||
|
let try_it = |kernel: &mut WorldKernel, speech: Option<&str>| {
|
||||||
|
kernel.submit(
|
||||||
|
command(
|
||||||
|
&active,
|
||||||
|
CommandId::new(),
|
||||||
|
caller.clone(),
|
||||||
|
CommandBody::ExerciseDecision {
|
||||||
|
opportunity: opportunity.clone(),
|
||||||
|
invocation: invocation(speech),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
&AuthenticatedCaller::fixture(caller.clone()),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
|
// Without an utterance the act is refused: the verb has no other way in.
|
||||||
|
assert!(try_it(&mut kernel, None).is_err());
|
||||||
|
// With one, the act commits and its words are a claim fact.
|
||||||
|
let receipt = try_it(&mut kernel, Some("We strike.")).expect("the attack commits");
|
||||||
|
assert!(matches!(receipt, SubmitReceipt::Applied(_)));
|
||||||
|
let event = kernel.state.events.last().unwrap();
|
||||||
|
assert_eq!(spoken(&kernel.state, event), Some("We strike."));
|
||||||
|
}
|
||||||
20
crates/ghostlight/src/verse/mod.rs
Normal file
20
crates/ghostlight/src/verse/mod.rs
Normal file
|
|
@ -0,0 +1,20 @@
|
||||||
|
//! The Aetheria verse run's own organs. The verse binary sits above this
|
||||||
|
//! module; here sit the parts of a run that belong to the library: the record
|
||||||
|
//! of every provider call and the spend it implies, the genesis of the
|
||||||
|
//! canonical verse world, and the manual run that advances it with its record.
|
||||||
|
|
||||||
|
mod calls;
|
||||||
|
mod genesis;
|
||||||
|
mod run;
|
||||||
|
|
||||||
|
pub use genesis::{CreateVerseWorldIntent, VerseGenesisError};
|
||||||
|
pub use calls::{
|
||||||
|
CALL_RECORD_SCHEMA, CallRecordError, CallRecordStore, Lane, LaneTokens, NodeSpend,
|
||||||
|
ProviderCallRecord, RecordingInferencePort, ReplayInferencePort, RunField, RunId, RunStart,
|
||||||
|
WaveSpend,
|
||||||
|
};
|
||||||
|
pub use run::{
|
||||||
|
RUN_RECORD_SCHEMA, RecordedKnobs, RunClaim, RunOutcome, RunStatus,
|
||||||
|
TickCheckpoint, TickReport, VerseRunConfig, VerseRunError, VerseRunRecord, VerseRunStore,
|
||||||
|
call_run_id, run_manual,
|
||||||
|
};
|
||||||
922
crates/ghostlight/src/verse/run.rs
Normal file
922
crates/ghostlight/src/verse/run.rs
Normal file
|
|
@ -0,0 +1,922 @@
|
||||||
|
//! The manual verse run: the tick driver and its record.
|
||||||
|
//!
|
||||||
|
//! One invocation advances the world tick by tick. A tick reads the world,
|
||||||
|
//! opens (or finds open) its tick document, which freezes one planned wave
|
||||||
|
//! (`plan_wave` over the derived hierarchy, with no focus), runs the frozen
|
||||||
|
//! cells through the wave runner (`run_frozen_cells`), advances the clock once
|
||||||
|
//! by the frozen span, and checkpoints. The driver owns the order of those
|
||||||
|
//! steps and nothing else: the planner chooses nodes and cells, cells decide
|
||||||
|
//! what factions do, the recording port owns spend, the kernel owns time.
|
||||||
|
//!
|
||||||
|
//! A tick is named by the world's clock-advance count, never by `now`. The
|
||||||
|
//! resume point is the open tick document (world, ordinal), written before the
|
||||||
|
//! tick's first cell and read by any later run: it froze the span, the knobs
|
||||||
|
//! and the cells (each with its node and distance) when the tick opened, so a
|
||||||
|
//! run under another span or knobs finishes the open tick as it was opened and
|
||||||
|
//! applies its own config from the next tick it opens. A tick whose cells did not all finish never
|
||||||
|
//! advances the clock, so the same ordinal, cells and command ids come back,
|
||||||
|
//! the controller-work rows pick up where they stopped, and the kernel answers
|
||||||
|
//! every re-submission with the original receipt. A run record reports a run
|
||||||
|
//! and is never read to resume one.
|
||||||
|
//!
|
||||||
|
//! A run starts only when it is invoked: nothing here waits, schedules or
|
||||||
|
//! repeats.
|
||||||
|
|
||||||
|
use super::calls::{RecordingInferencePort, WaveSpend, canonical};
|
||||||
|
use crate::cover::TickIndex;
|
||||||
|
use crate::wave::{
|
||||||
|
Deferral, DeferredNode, FrozenCell, Focus, GestaltKnobs, GestaltKnobsError, NodeReport, Refusal,
|
||||||
|
RefusalReason, UnattributedCall, WaveClock, WaveStop, act_line, acts_since,
|
||||||
|
deferred_nodes, node_reports, plan_wave, run_frozen_cells,
|
||||||
|
};
|
||||||
|
use crate::{
|
||||||
|
AgencyGraph, CommandId, ControllerRunner, DecisionOpportunity, FictionalMinutes, Hierarchy, MailboxError,
|
||||||
|
NodeId, OperatorEvent, SubjectId, TickMinutes, WorldId, WorldMailbox,
|
||||||
|
WorldSnapshot,
|
||||||
|
};
|
||||||
|
use chrono::Utc;
|
||||||
|
use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::{collections::BTreeMap, ops::ControlFlow, path::Path, sync::Mutex};
|
||||||
|
use thiserror::Error;
|
||||||
|
|
||||||
|
/// The run record document's schema.
|
||||||
|
pub const RUN_RECORD_SCHEMA: &str = "ghostlight.verse_run.v2";
|
||||||
|
const RUN_ROW: &str = "verse_run.v2";
|
||||||
|
/// The tick document's schema.
|
||||||
|
pub const TICK_RECORD_SCHEMA: &str = "ghostlight.verse_tick.v3";
|
||||||
|
const TICK_ROW: &str = "verse_tick.v3";
|
||||||
|
/// The schemas later ones replaced. No store holding one is read: the verse store
|
||||||
|
/// has never held a live run, so there is no migration, and a retired row is
|
||||||
|
/// refused by name.
|
||||||
|
const RETIRED_SCHEMAS: [&str; 3] = [
|
||||||
|
"ghostlight.verse_run.v1",
|
||||||
|
"ghostlight.verse_tick.v1",
|
||||||
|
"ghostlight.verse_tick.v2",
|
||||||
|
];
|
||||||
|
const CLOCK_NAMESPACE: &str = "ghostlight.verse.clock";
|
||||||
|
|
||||||
|
/// Why a run could not be recorded or started. Every variant names a kind of
|
||||||
|
/// fault; none carries a value the run held.
|
||||||
|
#[derive(Debug, Error)]
|
||||||
|
pub enum VerseRunError {
|
||||||
|
#[error("the run record store could not be read or written")]
|
||||||
|
Store,
|
||||||
|
#[error("the run record store holds a row that is not a canonical run record")]
|
||||||
|
Corrupt,
|
||||||
|
#[error("a run record's sequence is not an existing run or the next in its world")]
|
||||||
|
OutOfSequence,
|
||||||
|
#[error("the recording port belongs to another run")]
|
||||||
|
PortNotThisRun,
|
||||||
|
#[error("the run's configuration is not the one its claim recorded")]
|
||||||
|
ConfigNotThisClaim,
|
||||||
|
#[error("the world is not at the revision its claim was made from")]
|
||||||
|
WorldMovedSinceClaim,
|
||||||
|
#[error("the knobs are not valid: {0}")]
|
||||||
|
Knobs(#[from] GestaltKnobsError),
|
||||||
|
#[error("the run store holds a row of a retired schema (v1 run or tick); it is not migrated")]
|
||||||
|
RetiredSchema,
|
||||||
|
#[error(transparent)]
|
||||||
|
Mailbox(#[from] MailboxError),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where a run stands. `Running` is only ever the record of a run in flight,
|
||||||
|
/// or of one whose process died before it could say how it ended.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub enum RunStatus {
|
||||||
|
Running,
|
||||||
|
Completed,
|
||||||
|
/// A provider call could pass the token cap, so the run ended before the
|
||||||
|
/// open tick's clock advance.
|
||||||
|
BudgetExhausted,
|
||||||
|
/// The run ended without finishing its open tick. `reason` is a fixed code
|
||||||
|
/// naming the kind of fault, never a value.
|
||||||
|
Failed {
|
||||||
|
reason: String,
|
||||||
|
},
|
||||||
|
/// The caller asked the run to end after a finished tick.
|
||||||
|
Stopped,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A tick as the run left it. A closed tick has all its cells run and the
|
||||||
|
/// clock advanced by the tick's frozen span. The tick a run ended inside is
|
||||||
|
/// recorded too, unclosed, so what its cells committed is not lost; a later
|
||||||
|
/// run finds that tick's document open and works in it.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct TickCheckpoint {
|
||||||
|
/// The tick's ordinal, as its tick document names it.
|
||||||
|
pub tick: u64,
|
||||||
|
pub closed: bool,
|
||||||
|
pub cells: u32,
|
||||||
|
/// Every command the tick's cells hold a receipt for, in cell order. A
|
||||||
|
/// decline is a commit, so it is listed.
|
||||||
|
pub committed: Vec<CommandId>,
|
||||||
|
pub refusals: Vec<Refusal>,
|
||||||
|
/// The calls grouped cells received that named no handle, in cell order.
|
||||||
|
pub unattributed: Vec<UnattributedCall>,
|
||||||
|
/// Tokens the recording port charged during the tick.
|
||||||
|
pub tokens: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The knobs as a record carries them.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct RecordedKnobs {
|
||||||
|
/// Band periods in fictional minutes, by distance.
|
||||||
|
pub bands: Vec<u32>,
|
||||||
|
pub depth: u8,
|
||||||
|
pub max_node_turns: u16,
|
||||||
|
pub cells: u16,
|
||||||
|
pub constituent_cap: u16,
|
||||||
|
pub urgency_slots: u16,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RecordedKnobs {
|
||||||
|
pub fn of(knobs: &GestaltKnobs) -> Self {
|
||||||
|
Self {
|
||||||
|
bands: knobs.bands.iter().map(|band| band.minutes()).collect(),
|
||||||
|
depth: knobs.depth,
|
||||||
|
max_node_turns: knobs.max_node_turns,
|
||||||
|
cells: knobs.cover.cells,
|
||||||
|
constituent_cap: knobs.cover.constituent_cap,
|
||||||
|
urgency_slots: knobs.cover.urgency_slots,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What closed a tick.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub enum TickClose {
|
||||||
|
/// The run with this sequence submitted the tick's clock advance.
|
||||||
|
Clock { run: u64 },
|
||||||
|
/// A later run found the world's ordinal past the tick with the document
|
||||||
|
/// still open: its clock landed and the close was lost, or another clock
|
||||||
|
/// writer moved time.
|
||||||
|
World,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a tick decided when it opened. Document `ghostlight.verse_tick.v3`,
|
||||||
|
/// keyed (world, ordinal). Written once before the tick's first cell, closed
|
||||||
|
/// once, never reopened or deleted.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct VerseTick {
|
||||||
|
pub world_id: WorldId,
|
||||||
|
pub ordinal: u64,
|
||||||
|
pub opened_now: u64,
|
||||||
|
pub opened_revision: u64,
|
||||||
|
pub span_minutes: u32,
|
||||||
|
pub knobs: RecordedKnobs,
|
||||||
|
pub oversubscribed: bool,
|
||||||
|
pub cells: Vec<FrozenCell>,
|
||||||
|
/// The nodes the plan left out, with why: not due, or past the node-turn
|
||||||
|
/// bound. Written with the cells so a resumed tick reports what its wave
|
||||||
|
/// left out, not what a re-plan would.
|
||||||
|
pub deferred: Vec<(NodeId, Deferral)>,
|
||||||
|
pub opened_by_run: u64,
|
||||||
|
pub closed: Option<TickClose>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One invocation of the verse runner: what it was asked, what it did.
|
||||||
|
/// Document `ghostlight.verse_run.v2`, keyed (world, run sequence).
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct VerseRunRecord {
|
||||||
|
pub world_id: WorldId,
|
||||||
|
pub sequence: u64,
|
||||||
|
pub token_cap: u64,
|
||||||
|
pub ticks_requested: u32,
|
||||||
|
pub tick_span_minutes: u32,
|
||||||
|
pub knobs: RecordedKnobs,
|
||||||
|
/// The world's revision when the run began.
|
||||||
|
pub start_revision: u64,
|
||||||
|
pub checkpoints: Vec<TickCheckpoint>,
|
||||||
|
pub status: RunStatus,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VerseRunRecord {
|
||||||
|
/// The ticks this run finished: every cell run and the clock advanced.
|
||||||
|
pub fn ticks_closed(&self) -> usize {
|
||||||
|
self.checkpoints.iter().filter(|c| c.closed).count()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a caller asks of one run. The token cap is not here: the recording
|
||||||
|
/// port owns it.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct VerseRunConfig {
|
||||||
|
pub ticks: u32,
|
||||||
|
pub tick_span: TickMinutes,
|
||||||
|
pub knobs: GestaltKnobs,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A tick as the operator reads it, including the one a run ended inside.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct TickReport {
|
||||||
|
pub checkpoint: TickCheckpoint,
|
||||||
|
/// The tick's nodes in run order, each with its acts and refusals.
|
||||||
|
pub nodes: Vec<NodeReport>,
|
||||||
|
/// The labels of the subjects the checkpoint's refusals name, from the
|
||||||
|
/// snapshot the tick opened on.
|
||||||
|
pub labels: BTreeMap<SubjectId, String>,
|
||||||
|
/// What this invocation's calls for the tick's cells cost, by lane and node.
|
||||||
|
pub spend: WaveSpend,
|
||||||
|
/// Nodes that took no turn this tick, and why: the plan left them out, or
|
||||||
|
/// the window's allowance ran out first.
|
||||||
|
pub deferred: Vec<DeferredNode>,
|
||||||
|
pub spent: u64,
|
||||||
|
pub remaining: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TickReport {
|
||||||
|
/// Every act the tick committed, grouped by node in run order.
|
||||||
|
pub fn acts(&self) -> impl Iterator<Item = &OperatorEvent> {
|
||||||
|
self.nodes.iter().flat_map(|node| node.acts.iter())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Display for RunStatus {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::Running => f.write_str("Running"),
|
||||||
|
Self::Completed => f.write_str("Completed"),
|
||||||
|
Self::BudgetExhausted => f.write_str("BudgetExhausted"),
|
||||||
|
Self::Failed { reason } => write!(f, "Failed ({reason})"),
|
||||||
|
Self::Stopped => f.write_str("Stopped"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The tick as the operator reads it: a header, then per node its label,
|
||||||
|
/// distance and spend, one line per committed act (who, which verb, how it
|
||||||
|
/// renders, what its roles are bound to, what was said or shown) and one per
|
||||||
|
/// refusal, then the spend.
|
||||||
|
impl std::fmt::Display for TickReport {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
let checkpoint = &self.checkpoint;
|
||||||
|
writeln!(
|
||||||
|
f,
|
||||||
|
"tick {} {}: {} cells, {} acts, {} refused",
|
||||||
|
checkpoint.tick,
|
||||||
|
if checkpoint.closed { "closed" } else { "open" },
|
||||||
|
checkpoint.cells,
|
||||||
|
self.acts().count(),
|
||||||
|
checkpoint.refusals.len()
|
||||||
|
)?;
|
||||||
|
for node in &self.nodes {
|
||||||
|
match node.distance {
|
||||||
|
Some(distance) => {
|
||||||
|
writeln!(f, " node {} (distance {distance}): {} tokens", node.label, node.spent)?
|
||||||
|
}
|
||||||
|
None => writeln!(f, " node {}: {} tokens", node.label, node.spent)?,
|
||||||
|
}
|
||||||
|
for act in &node.acts {
|
||||||
|
writeln!(f, " {}", act_line(act))?;
|
||||||
|
}
|
||||||
|
for refusal in &node.refusals {
|
||||||
|
let reason = match refusal.reason {
|
||||||
|
RefusalReason::Interrupted => "interrupted",
|
||||||
|
RefusalReason::WorldRejected => "world_rejected",
|
||||||
|
RefusalReason::OpportunityGone => "opportunity_gone",
|
||||||
|
RefusalReason::ScopeMoved => "scope_moved",
|
||||||
|
RefusalReason::ProposalUndecodable => "proposal_undecodable",
|
||||||
|
RefusalReason::RowDisagreesWithCell => "row_disagrees_with_cell",
|
||||||
|
RefusalReason::CallUnattributed => "call_unattributed",
|
||||||
|
};
|
||||||
|
let label = self.labels.get(&refusal.subject).map_or("-", String::as_str);
|
||||||
|
writeln!(f, " refused: cell {} {label} {reason}", refusal.cell)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for call in &checkpoint.unattributed {
|
||||||
|
writeln!(f, " note: cell {} call names no handle: tool {:?}", call.cell, call.tool)?;
|
||||||
|
}
|
||||||
|
for (reason, name) in [
|
||||||
|
(Deferral::NotDue, "not due"),
|
||||||
|
(Deferral::OverBound, "over the node-turn bound"),
|
||||||
|
(Deferral::Allowance, "past the allowance"),
|
||||||
|
] {
|
||||||
|
let labels: Vec<&str> = self
|
||||||
|
.deferred
|
||||||
|
.iter()
|
||||||
|
.filter(|node| node.reason == reason)
|
||||||
|
.map(|node| node.label.as_str())
|
||||||
|
.collect();
|
||||||
|
if !labels.is_empty() {
|
||||||
|
writeln!(f, " deferred ({name}): {}", labels.join(", "))?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
writeln!(
|
||||||
|
f,
|
||||||
|
" tokens: {} this tick, {} spent, {} remaining",
|
||||||
|
checkpoint.tokens, self.spent, self.remaining
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct RunOutcome {
|
||||||
|
pub record: VerseRunRecord,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn row_key(world: WorldId, sequence: u64) -> String {
|
||||||
|
format!("{}/{sequence:020}", world.key())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn tick_key(world: WorldId, ordinal: u64) -> String {
|
||||||
|
format!("{}/{ordinal:020}", world.key())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn tick_row(tick: &VerseTick) -> Result<CultCacheEnvelope, VerseRunError> {
|
||||||
|
Ok(CultCacheEnvelope {
|
||||||
|
key: tick_key(tick.world_id, tick.ordinal),
|
||||||
|
r#type: TICK_ROW.into(),
|
||||||
|
payload: rmp_serde::to_vec_named(tick).map_err(|_| VerseRunError::Store)?,
|
||||||
|
stored_at: Utc::now().to_rfc3339(),
|
||||||
|
schema_id: Some(TICK_RECORD_SCHEMA.into()),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run_row(record: &VerseRunRecord) -> Result<CultCacheEnvelope, VerseRunError> {
|
||||||
|
Ok(CultCacheEnvelope {
|
||||||
|
key: row_key(record.world_id, record.sequence),
|
||||||
|
r#type: RUN_ROW.into(),
|
||||||
|
payload: rmp_serde::to_vec_named(record).map_err(|_| VerseRunError::Store)?,
|
||||||
|
stored_at: Utc::now().to_rfc3339(),
|
||||||
|
schema_id: Some(RUN_RECORD_SCHEMA.into()),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A run's number and cap, claimed from the run store before anything of the
|
||||||
|
/// run exists. The call ledger's run id derives from it ([`call_run_id`]), and
|
||||||
|
/// [`run_manual`] runs only the record it names. Not `Clone`: a claim runs once
|
||||||
|
/// or is abandoned.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct RunClaim {
|
||||||
|
world_id: WorldId,
|
||||||
|
sequence: u64,
|
||||||
|
token_cap: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RunClaim {
|
||||||
|
/// The run's number, the one [`call_run_id`] names.
|
||||||
|
pub fn sequence(&self) -> u64 {
|
||||||
|
self.sequence
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every row of the file, split by type.
|
||||||
|
struct Rows {
|
||||||
|
runs: Vec<VerseRunRecord>,
|
||||||
|
ticks: Vec<VerseTick>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run records and tick documents in one CultCache file. A run is claimed
|
||||||
|
/// when it begins and saved again each time it moves, so a row is replaced by
|
||||||
|
/// its own later state. A tick is opened once and closed once, and only by the tick
|
||||||
|
/// driver: the writers are private to this module.
|
||||||
|
///
|
||||||
|
/// ```compile_fail
|
||||||
|
/// fn wedge(store: &ghostlight::VerseRunStore, world: ghostlight::WorldId) {
|
||||||
|
/// store.close_ticks_before(world, 1).unwrap();
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
pub struct VerseRunStore {
|
||||||
|
store: Mutex<OwnedRedbMessagePackBackingStore>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VerseRunStore {
|
||||||
|
/// Opens the file, creating it empty when absent. Every row must be a
|
||||||
|
/// canonical run record of this schema under its own key.
|
||||||
|
pub fn open(path: impl AsRef<Path>) -> Result<Self, VerseRunError> {
|
||||||
|
let store = OwnedRedbMessagePackBackingStore::new(path.as_ref())
|
||||||
|
.map_err(|_| VerseRunError::Store)?;
|
||||||
|
store
|
||||||
|
.validate_path_identity()
|
||||||
|
.map_err(|_| VerseRunError::Store)?;
|
||||||
|
let opened = Self {
|
||||||
|
store: Mutex::new(store),
|
||||||
|
};
|
||||||
|
opened.records()?;
|
||||||
|
Ok(opened)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn records(&self) -> Result<Rows, VerseRunError> {
|
||||||
|
let rows = self
|
||||||
|
.store
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| VerseRunError::Store)?
|
||||||
|
.pull_all()
|
||||||
|
.map_err(|_| VerseRunError::Store)?;
|
||||||
|
let mut runs = Vec::new();
|
||||||
|
let mut ticks = Vec::new();
|
||||||
|
for row in &rows {
|
||||||
|
match (row.r#type.as_str(), row.schema_id.as_deref()) {
|
||||||
|
(RUN_ROW, Some(RUN_RECORD_SCHEMA)) => {
|
||||||
|
let record: VerseRunRecord =
|
||||||
|
canonical(row).map_err(|_| VerseRunError::Corrupt)?;
|
||||||
|
if row.key != row_key(record.world_id, record.sequence)
|
||||||
|
|| record.sequence == 0
|
||||||
|
{
|
||||||
|
return Err(VerseRunError::Corrupt);
|
||||||
|
}
|
||||||
|
runs.push(record);
|
||||||
|
}
|
||||||
|
(TICK_ROW, Some(TICK_RECORD_SCHEMA)) => {
|
||||||
|
let tick: VerseTick = canonical(row).map_err(|_| VerseRunError::Corrupt)?;
|
||||||
|
if row.key != tick_key(tick.world_id, tick.ordinal) {
|
||||||
|
return Err(VerseRunError::Corrupt);
|
||||||
|
}
|
||||||
|
ticks.push(tick);
|
||||||
|
}
|
||||||
|
(_, Some(schema)) if RETIRED_SCHEMAS.contains(&schema) => {
|
||||||
|
return Err(VerseRunError::RetiredSchema);
|
||||||
|
}
|
||||||
|
_ => return Err(VerseRunError::Corrupt),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
runs.sort_by_key(|record| (record.world_id.key(), record.sequence));
|
||||||
|
ticks.sort_by_key(|tick| (tick.world_id.key(), tick.ordinal));
|
||||||
|
Ok(Rows { runs, ticks })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The sequence the next claim of this world takes. Sequences count from
|
||||||
|
/// one. Private: a caller never chooses a run's number, `claim` does.
|
||||||
|
fn next_sequence(&self, world: WorldId) -> Result<u64, VerseRunError> {
|
||||||
|
Ok(self
|
||||||
|
.records()?
|
||||||
|
.runs
|
||||||
|
.iter()
|
||||||
|
.filter(|record| record.world_id == world)
|
||||||
|
.map(|record| record.sequence)
|
||||||
|
.max()
|
||||||
|
.unwrap_or(0)
|
||||||
|
+ 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every run of the world, in sequence.
|
||||||
|
pub fn runs(&self, world: WorldId) -> Result<Vec<VerseRunRecord>, VerseRunError> {
|
||||||
|
Ok(self
|
||||||
|
.records()?
|
||||||
|
.runs
|
||||||
|
.into_iter()
|
||||||
|
.filter(|record| record.world_id == world)
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The tick document of (world, ordinal), when one was opened.
|
||||||
|
pub fn tick(&self, world: WorldId, ordinal: u64) -> Result<Option<VerseTick>, VerseRunError> {
|
||||||
|
Ok(self
|
||||||
|
.records()?
|
||||||
|
.ticks
|
||||||
|
.into_iter()
|
||||||
|
.find(|tick| tick.world_id == world && tick.ordinal == ordinal))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes a tick document that does not exist yet, open. The store's own
|
||||||
|
/// insert-if-absent decides, so two opens of one ordinal cannot both win.
|
||||||
|
/// Private: the tick driver is the only writer of tick rows.
|
||||||
|
fn open_tick(&self, tick: &VerseTick) -> Result<(), VerseRunError> {
|
||||||
|
if tick.closed.is_some() {
|
||||||
|
return Err(VerseRunError::OutOfSequence);
|
||||||
|
}
|
||||||
|
let row = tick_row(tick)?;
|
||||||
|
let inserted = self
|
||||||
|
.store
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| VerseRunError::Store)?
|
||||||
|
.insert_entry_if_absent(row)
|
||||||
|
.map_err(|_| VerseRunError::Store)?;
|
||||||
|
if inserted {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(VerseRunError::OutOfSequence)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Closes an open tick document. Private, like every tick writer.
|
||||||
|
fn close_tick(
|
||||||
|
&self,
|
||||||
|
world: WorldId,
|
||||||
|
ordinal: u64,
|
||||||
|
close: TickClose,
|
||||||
|
) -> Result<(), VerseRunError> {
|
||||||
|
let Some(mut tick) = self.tick(world, ordinal)? else {
|
||||||
|
return Err(VerseRunError::OutOfSequence);
|
||||||
|
};
|
||||||
|
if tick.closed.is_some() {
|
||||||
|
return Err(VerseRunError::OutOfSequence);
|
||||||
|
}
|
||||||
|
tick.closed = Some(close);
|
||||||
|
self.put_tick(&tick)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Closes, as the world's, every open tick of the world below `ordinal`.
|
||||||
|
fn close_ticks_before(&self, world: WorldId, ordinal: u64) -> Result<(), VerseRunError> {
|
||||||
|
for mut tick in self.records()?.ticks {
|
||||||
|
if tick.world_id == world && tick.ordinal < ordinal && tick.closed.is_none() {
|
||||||
|
tick.closed = Some(TickClose::World);
|
||||||
|
self.put_tick(&tick)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn put_tick(&self, tick: &VerseTick) -> Result<(), VerseRunError> {
|
||||||
|
let row = tick_row(tick)?;
|
||||||
|
self.store
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| VerseRunError::Store)?
|
||||||
|
.push(&row)
|
||||||
|
.map_err(|_| VerseRunError::Store)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Claims the next run of the snapshot's world: writes its `Running`
|
||||||
|
/// record, with the cap and config it was claimed under, in one insert that
|
||||||
|
/// cannot overwrite a record. The returned claim is the only way to run it;
|
||||||
|
/// a claim that never runs stays `Running` (a process that died) or is
|
||||||
|
/// ended by [`abandon`](Self::abandon), and its number is never issued
|
||||||
|
/// again.
|
||||||
|
pub fn claim(
|
||||||
|
&self,
|
||||||
|
snapshot: &WorldSnapshot,
|
||||||
|
token_cap: u64,
|
||||||
|
config: &VerseRunConfig,
|
||||||
|
) -> Result<RunClaim, VerseRunError> {
|
||||||
|
config.knobs.validate()?;
|
||||||
|
let record = VerseRunRecord {
|
||||||
|
world_id: snapshot.world_id,
|
||||||
|
sequence: self.next_sequence(snapshot.world_id)?,
|
||||||
|
token_cap,
|
||||||
|
ticks_requested: config.ticks,
|
||||||
|
tick_span_minutes: config.tick_span.minutes(),
|
||||||
|
knobs: RecordedKnobs::of(&config.knobs),
|
||||||
|
start_revision: snapshot.revision,
|
||||||
|
checkpoints: Vec::new(),
|
||||||
|
status: RunStatus::Running,
|
||||||
|
};
|
||||||
|
self.insert_run(&record)?;
|
||||||
|
Ok(RunClaim {
|
||||||
|
world_id: record.world_id,
|
||||||
|
sequence: record.sequence,
|
||||||
|
token_cap,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes a run record that does not exist yet. The store's own
|
||||||
|
/// insert-if-absent decides, so two claims of one sequence cannot both win.
|
||||||
|
fn insert_run(&self, record: &VerseRunRecord) -> Result<(), VerseRunError> {
|
||||||
|
let inserted = self
|
||||||
|
.store
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| VerseRunError::Store)?
|
||||||
|
.insert_entry_if_absent(run_row(record)?)
|
||||||
|
.map_err(|_| VerseRunError::Store)?;
|
||||||
|
if inserted {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(VerseRunError::OutOfSequence)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Ends a claim that never ran: its record becomes `Failed { reason }`.
|
||||||
|
pub fn abandon(&self, claim: RunClaim, reason: &'static str) -> Result<(), VerseRunError> {
|
||||||
|
let mut record = self.claimed(&claim)?;
|
||||||
|
record.status = failed(reason);
|
||||||
|
self.save(&record)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The record a claim names.
|
||||||
|
fn claimed(&self, claim: &RunClaim) -> Result<VerseRunRecord, VerseRunError> {
|
||||||
|
self.records()?
|
||||||
|
.runs
|
||||||
|
.into_iter()
|
||||||
|
.find(|record| record.world_id == claim.world_id && record.sequence == claim.sequence)
|
||||||
|
.ok_or(VerseRunError::OutOfSequence)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Replaces a claimed record with its later state. A sequence with no
|
||||||
|
/// record is refused: only `claim` creates one.
|
||||||
|
fn save(&self, record: &VerseRunRecord) -> Result<(), VerseRunError> {
|
||||||
|
self.claimed(&RunClaim {
|
||||||
|
world_id: record.world_id,
|
||||||
|
sequence: record.sequence,
|
||||||
|
token_cap: record.token_cap,
|
||||||
|
})?;
|
||||||
|
self.store
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| VerseRunError::Store)?
|
||||||
|
.push(&run_row(record)?)
|
||||||
|
.map_err(|_| VerseRunError::Store)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enum TickEnd {
|
||||||
|
/// Every cell finished and the clock advanced.
|
||||||
|
Closed,
|
||||||
|
/// The run ends inside this tick with this status.
|
||||||
|
Open(RunStatus),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The run status a wave's stop ends the run with.
|
||||||
|
fn status_of(stop: WaveStop) -> RunStatus {
|
||||||
|
match stop {
|
||||||
|
WaveStop::Budget => RunStatus::BudgetExhausted,
|
||||||
|
WaveStop::Fault(code) => failed(code),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn failed(reason: &str) -> RunStatus {
|
||||||
|
RunStatus::Failed {
|
||||||
|
reason: reason.to_owned(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs `config.ticks` ticks from the world's present clock under the cap the
|
||||||
|
/// recording port was opened with. `observe` sees each tick as it ends,
|
||||||
|
/// including the one a run ends inside, and may stop the run after a finished
|
||||||
|
/// tick by breaking. `claim` is the run's number from
|
||||||
|
/// [`VerseRunStore::claim`]; the port must have been opened for it
|
||||||
|
/// ([`call_run_id`]) under the cap the claim recorded, and `config` is the one
|
||||||
|
/// the claim was made with. A claim this refuses is abandoned, so a refused
|
||||||
|
/// start binds nothing.
|
||||||
|
pub async fn run_manual(
|
||||||
|
mailbox: &WorldMailbox,
|
||||||
|
runner: &ControllerRunner,
|
||||||
|
port: &RecordingInferencePort,
|
||||||
|
store: &VerseRunStore,
|
||||||
|
claim: RunClaim,
|
||||||
|
config: &VerseRunConfig,
|
||||||
|
mut observe: impl FnMut(&TickReport) -> ControlFlow<()>,
|
||||||
|
) -> Result<RunOutcome, VerseRunError> {
|
||||||
|
let begun = match mailbox.snapshot().await {
|
||||||
|
Ok(begun) => begun,
|
||||||
|
Err(error) => {
|
||||||
|
store.abandon(claim, "world_unavailable")?;
|
||||||
|
return Err(error.into());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if port.run_id() != &call_run_id(claim.sequence)
|
||||||
|
|| port.cap() != claim.token_cap
|
||||||
|
|| begun.world_id != claim.world_id
|
||||||
|
{
|
||||||
|
store.abandon(claim, "port_not_this_run")?;
|
||||||
|
return Err(VerseRunError::PortNotThisRun);
|
||||||
|
}
|
||||||
|
let sequence = claim.sequence;
|
||||||
|
let mut record = store.claimed(&claim)?;
|
||||||
|
if config.knobs.validate().is_err() || !record_matches(&record, config) {
|
||||||
|
store.abandon(claim, "config_not_this_claim")?;
|
||||||
|
return Err(VerseRunError::ConfigNotThisClaim);
|
||||||
|
}
|
||||||
|
// The record names the revision the run started from, so the run starts
|
||||||
|
// from it.
|
||||||
|
if record.start_revision != begun.revision {
|
||||||
|
store.abandon(claim, "world_moved_since_claim")?;
|
||||||
|
return Err(VerseRunError::WorldMovedSinceClaim);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut spent_before = port.spent();
|
||||||
|
for completed in 0..config.ticks {
|
||||||
|
let (end, report) = run_tick(
|
||||||
|
mailbox,
|
||||||
|
runner,
|
||||||
|
port,
|
||||||
|
store,
|
||||||
|
sequence,
|
||||||
|
config,
|
||||||
|
spent_before,
|
||||||
|
|| mailbox.operator_log(),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
spent_before = port.spent();
|
||||||
|
match end {
|
||||||
|
TickEnd::Open(status) => {
|
||||||
|
record.status = status;
|
||||||
|
if let Some(report) = report {
|
||||||
|
record.checkpoints.push(report.checkpoint.clone());
|
||||||
|
store.save(&record)?;
|
||||||
|
let _ = observe(&report);
|
||||||
|
} else {
|
||||||
|
store.save(&record)?;
|
||||||
|
}
|
||||||
|
return Ok(RunOutcome { record });
|
||||||
|
}
|
||||||
|
TickEnd::Closed => {
|
||||||
|
let report = report.expect("a closed tick has its report");
|
||||||
|
record.checkpoints.push(report.checkpoint.clone());
|
||||||
|
store.save(&record)?;
|
||||||
|
if observe(&report).is_break() && completed + 1 < config.ticks {
|
||||||
|
record.status = RunStatus::Stopped;
|
||||||
|
store.save(&record)?;
|
||||||
|
return Ok(RunOutcome { record });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
record.status = RunStatus::Completed;
|
||||||
|
store.save(&record)?;
|
||||||
|
Ok(RunOutcome { record })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the record a claim wrote was made under this config.
|
||||||
|
fn record_matches(record: &VerseRunRecord, config: &VerseRunConfig) -> bool {
|
||||||
|
record.ticks_requested == config.ticks
|
||||||
|
&& record.tick_span_minutes == config.tick_span.minutes()
|
||||||
|
&& record.knobs == RecordedKnobs::of(&config.knobs)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The key a run's provider calls are recorded under: the run's sequence, so a
|
||||||
|
/// run record and its call records name each other.
|
||||||
|
pub fn call_run_id(sequence: u64) -> super::RunId {
|
||||||
|
super::RunId::new(&format!("run-{sequence}"))
|
||||||
|
.expect("a decimal sequence is a canonical run id")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The id of a tick's clock advance: the world and the ordinal, nothing the
|
||||||
|
/// run holds. A retry in the same tick has the same body and is answered
|
||||||
|
/// `AlreadyApplied`.
|
||||||
|
pub(crate) fn clock_command_id(world: WorldId, ordinal: u64) -> CommandId {
|
||||||
|
CommandId::derived(CLOCK_NAMESPACE, &[&world.text(), &ordinal.to_string()])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One tick. The report is absent only when the world or the tick document
|
||||||
|
/// could not be read at all.
|
||||||
|
async fn run_tick<ReadLog, Log>(
|
||||||
|
mailbox: &WorldMailbox,
|
||||||
|
runner: &ControllerRunner,
|
||||||
|
port: &RecordingInferencePort,
|
||||||
|
store: &VerseRunStore,
|
||||||
|
sequence: u64,
|
||||||
|
config: &VerseRunConfig,
|
||||||
|
spent_before: u64,
|
||||||
|
read_log: ReadLog,
|
||||||
|
) -> (TickEnd, Option<TickReport>)
|
||||||
|
where
|
||||||
|
ReadLog: FnOnce() -> Log,
|
||||||
|
Log: Future<Output = Result<Vec<OperatorEvent>, MailboxError>>,
|
||||||
|
{
|
||||||
|
let read = async {
|
||||||
|
let snapshot = mailbox.snapshot().await?;
|
||||||
|
let ordinal = mailbox.clock_advances().await?;
|
||||||
|
let opportunities = mailbox.opportunities().await?;
|
||||||
|
let graph = mailbox.agency_graph().await?;
|
||||||
|
let hierarchy = mailbox.hierarchy().await?;
|
||||||
|
Ok::<_, MailboxError>((snapshot, ordinal, opportunities, graph, hierarchy))
|
||||||
|
}
|
||||||
|
.await;
|
||||||
|
let Ok((snapshot, ordinal, opportunities, graph, hierarchy)) = read else {
|
||||||
|
return (TickEnd::Open(failed("world_unavailable")), None);
|
||||||
|
};
|
||||||
|
let world = snapshot.world_id;
|
||||||
|
let Ok(tick) = open_or_find(
|
||||||
|
store,
|
||||||
|
ordinal,
|
||||||
|
sequence,
|
||||||
|
config,
|
||||||
|
&snapshot,
|
||||||
|
&opportunities,
|
||||||
|
&graph,
|
||||||
|
&hierarchy,
|
||||||
|
) else {
|
||||||
|
return (TickEnd::Open(failed("run_store")), None);
|
||||||
|
};
|
||||||
|
let index = TickIndex(ordinal);
|
||||||
|
let Some(span) = TickMinutes::new(tick.span_minutes) else {
|
||||||
|
return (TickEnd::Open(failed("run_store")), None);
|
||||||
|
};
|
||||||
|
|
||||||
|
let outcome = run_frozen_cells(mailbox, runner, index, &tick.cells).await;
|
||||||
|
let mut open = outcome.stop.map(status_of);
|
||||||
|
|
||||||
|
// The act listing is the tick's report to the operator: a tick whose log
|
||||||
|
// cannot be read is not closed, and the run ends there.
|
||||||
|
let acts = match acts_since(read_log().await, snapshot.revision) {
|
||||||
|
Some(acts) => acts,
|
||||||
|
None => {
|
||||||
|
open = Some(failed("operator_log_unavailable"));
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// So is a tick whose calls cannot be read back: its nodes' spend is the
|
||||||
|
// report's, and the ledger and the world must agree before time moves.
|
||||||
|
let spend = match port
|
||||||
|
.records()
|
||||||
|
.ok()
|
||||||
|
.and_then(|records| WaveSpend::of(&records, world, index, &tick.cells).ok())
|
||||||
|
{
|
||||||
|
Some(spend) => spend,
|
||||||
|
None => {
|
||||||
|
open = Some(failed("call_records_unavailable"));
|
||||||
|
WaveSpend::default()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if open.is_none() {
|
||||||
|
if mailbox
|
||||||
|
.submit_clock(clock_command_id(world, ordinal), span)
|
||||||
|
.await
|
||||||
|
.is_err()
|
||||||
|
{
|
||||||
|
open = Some(failed("clock_refused"));
|
||||||
|
} else if store
|
||||||
|
.close_tick(world, ordinal, TickClose::Clock { run: sequence })
|
||||||
|
.is_err()
|
||||||
|
{
|
||||||
|
open = Some(failed("run_store"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let spent = port.spent();
|
||||||
|
let checkpoint_closed = open.is_none();
|
||||||
|
let mut checkpoint = TickCheckpoint {
|
||||||
|
tick: ordinal,
|
||||||
|
closed: checkpoint_closed,
|
||||||
|
cells: tick.cells.len() as u32,
|
||||||
|
committed: Vec::new(),
|
||||||
|
refusals: Vec::new(),
|
||||||
|
unattributed: Vec::new(),
|
||||||
|
tokens: spent.saturating_sub(spent_before),
|
||||||
|
};
|
||||||
|
for node in &outcome.nodes {
|
||||||
|
checkpoint.committed.extend(node.committed.iter().copied());
|
||||||
|
checkpoint.refusals.extend(node.refusals.iter().copied());
|
||||||
|
checkpoint.unattributed.extend(node.unattributed.iter().cloned());
|
||||||
|
}
|
||||||
|
let labels = checkpoint
|
||||||
|
.refusals
|
||||||
|
.iter()
|
||||||
|
.filter_map(|refusal| {
|
||||||
|
snapshot
|
||||||
|
.subjects
|
||||||
|
.iter()
|
||||||
|
.find(|subject| subject.id == refusal.subject)
|
||||||
|
.map(|subject| (refusal.subject, subject.label.clone()))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let report = TickReport {
|
||||||
|
nodes: node_reports(&tick.cells, &outcome, acts, &spend, &snapshot, &hierarchy),
|
||||||
|
deferred: deferred_nodes(&tick.deferred, &tick.cells, &outcome, &snapshot, &hierarchy),
|
||||||
|
spend,
|
||||||
|
checkpoint,
|
||||||
|
labels,
|
||||||
|
spent,
|
||||||
|
remaining: port.cap().saturating_sub(spent),
|
||||||
|
};
|
||||||
|
(open.map_or(TickEnd::Closed, TickEnd::Open), Some(report))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The tick document for `ordinal`: the open one a run left, or a new one
|
||||||
|
/// frozen from a wave planned now over the derived hierarchy with no focus. An
|
||||||
|
/// open tick the world has moved past is closed as the world's first. A
|
||||||
|
/// document already closed at the world's current ordinal is a store that
|
||||||
|
/// disagrees with the world.
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
fn open_or_find(
|
||||||
|
store: &VerseRunStore,
|
||||||
|
ordinal: u64,
|
||||||
|
sequence: u64,
|
||||||
|
config: &VerseRunConfig,
|
||||||
|
snapshot: &WorldSnapshot,
|
||||||
|
opportunities: &[DecisionOpportunity],
|
||||||
|
graph: &AgencyGraph,
|
||||||
|
hierarchy: &Hierarchy,
|
||||||
|
) -> Result<VerseTick, VerseRunError> {
|
||||||
|
let world = snapshot.world_id;
|
||||||
|
store.close_ticks_before(world, ordinal)?;
|
||||||
|
if let Some(tick) = store.tick(world, ordinal)? {
|
||||||
|
return if tick.closed.is_none() {
|
||||||
|
Ok(tick)
|
||||||
|
} else {
|
||||||
|
Err(VerseRunError::OutOfSequence)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
let wave = plan_wave(
|
||||||
|
WaveClock {
|
||||||
|
world,
|
||||||
|
ordinal: TickIndex(ordinal),
|
||||||
|
now: FictionalMinutes(snapshot.now.0),
|
||||||
|
},
|
||||||
|
hierarchy,
|
||||||
|
opportunities,
|
||||||
|
graph,
|
||||||
|
&Focus::default(),
|
||||||
|
&[],
|
||||||
|
&config.knobs,
|
||||||
|
)?;
|
||||||
|
let tick = VerseTick {
|
||||||
|
world_id: world,
|
||||||
|
ordinal,
|
||||||
|
opened_now: snapshot.now.0,
|
||||||
|
opened_revision: snapshot.revision,
|
||||||
|
span_minutes: config.tick_span.minutes(),
|
||||||
|
knobs: RecordedKnobs::of(&config.knobs),
|
||||||
|
oversubscribed: wave.turns.iter().any(|turn| turn.oversubscribed),
|
||||||
|
cells: wave.frozen(),
|
||||||
|
deferred: wave.deferred,
|
||||||
|
opened_by_run: sequence,
|
||||||
|
closed: None,
|
||||||
|
};
|
||||||
|
store.open_tick(&tick)?;
|
||||||
|
Ok(tick)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests;
|
||||||
3224
crates/ghostlight/src/verse/run/tests.rs
Normal file
3224
crates/ghostlight/src/verse/run/tests.rs
Normal file
File diff suppressed because it is too large
Load diff
1383
crates/ghostlight/src/wave.rs
Normal file
1383
crates/ghostlight/src/wave.rs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -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,
|
||||||
)
|
)
|
||||||
|
|
|
||||||
BIN
crates/ghostlight/tests/fixtures/aetheria-verse-catalog.cc
vendored
Normal file
BIN
crates/ghostlight/tests/fixtures/aetheria-verse-catalog.cc
vendored
Normal file
Binary file not shown.
16
crates/ghostlight/tests/fixtures/aetheria-verse-catalog.provenance.txt
vendored
Normal file
16
crates/ghostlight/tests/fixtures/aetheria-verse-catalog.provenance.txt
vendored
Normal file
|
|
@ -0,0 +1,16 @@
|
||||||
|
aetheria-verse-catalog.cc was written by Aetheria's own types, not by hand and not by Ghostlight.
|
||||||
|
|
||||||
|
Writer: tests/Aetheria.Shared.Tests/VerseGrammarTests.cs, WriteFixture (xunit test
|
||||||
|
Fixture_writer_is_deterministic_and_emits_what_the_grammar_reader_needs),
|
||||||
|
which authors VerseGrammar, three VerseVerb and two Faction records through
|
||||||
|
Aetheria's CultCache types and leaves the file at AETHERIA_VERSE_FIXTURE_PATH.
|
||||||
|
Aetheria: GameCult/Aetheria origin/master 92b82e9aa5bb422c568c4bfc85a8f641426a41fc
|
||||||
|
(contains aetheria-release cut verse-grammar, merged at 35af2930).
|
||||||
|
Command: AETHERIA_VERSE_FIXTURE_PATH=/tmp/aetheria-verse-catalog.cc
|
||||||
|
dotnet test tests/Aetheria.Shared.Tests
|
||||||
|
-p:CultLibRoot=<CultLib 45c2f40 clone> -p:CultMathRoot=<CultLib 252e226c clone>
|
||||||
|
--filter "FullyQualifiedName~Fixture_writer_is_deterministic"
|
||||||
|
run on Yggdrasil through the verify stopgap (dotnet/sdk:10.0), 2026-10-10.
|
||||||
|
Content: six records; two writes of the writer agree on content, though not bytes
|
||||||
|
(CultCache stamps storedAt from the wall clock). Regenerate and diff on content,
|
||||||
|
never hand-edit.
|
||||||
BIN
crates/ghostlight/tests/fixtures/base_world.cc
vendored
Normal file
BIN
crates/ghostlight/tests/fixtures/base_world.cc
vendored
Normal file
Binary file not shown.
3
crates/ghostlight/tests/fixtures/base_world.digests
vendored
Normal file
3
crates/ghostlight/tests/fixtures/base_world.digests
vendored
Normal file
|
|
@ -0,0 +1,3 @@
|
||||||
|
3
|
||||||
|
sha256:b706f57cb417603366a1f47a5dd099fbf68bfecc5b2e8d61d281630791d1d76d
|
||||||
|
sha256:2039956a26c3d5b073d101e5898ac5a60a9eb63a3b93f447b2d8f78ef4caf979
|
||||||
1
crates/ghostlight/tests/fixtures/base_world.id
vendored
Normal file
1
crates/ghostlight/tests/fixtures/base_world.id
vendored
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
"a534b32a-4d00-429c-bf6c-ce1d55385380"
|
||||||
|
|
@ -1,21 +1,12 @@
|
||||||
schema = "gamecult.idunn.target_declaration.v1"
|
schema = "gamecult.idunn.target_declaration.v1"
|
||||||
target = "ghostlight"
|
target = "ghostlight"
|
||||||
source_stamp_environment = "GHOSTLIGHT_BUILD_COMMIT"
|
source_stamp_environment = "GHOSTLIGHT_BUILD_COMMIT"
|
||||||
required_gitlinks = ["vendor/eve"]
|
|
||||||
|
|
||||||
[[steps]]
|
# The Dungeon is one binary: the page is compiled into it, so there is no
|
||||||
id = "test-persona-boundary"
|
# adjacent artifact. The connector key is not declared here: the operator
|
||||||
phase = "test"
|
# binding's [workload.secret_files] entry GHOSTLIGHT_CONNECTOR_KEY_FILE is what
|
||||||
runner = "rust-build"
|
# Idunn loads as a systemd credential, and the recipe only names the variable
|
||||||
required_environment = ["CARGO_HOME", "HOME"]
|
# that then holds the credential's path.
|
||||||
argv = ["cargo", "test", "--locked", "-p", "ghostlight-persona-projection"]
|
|
||||||
|
|
||||||
[[steps]]
|
|
||||||
id = "test-world-library"
|
|
||||||
phase = "test"
|
|
||||||
runner = "rust-build"
|
|
||||||
required_environment = ["CARGO_HOME", "HOME"]
|
|
||||||
argv = ["cargo", "test", "--locked", "-p", "ghostlight"]
|
|
||||||
|
|
||||||
[[steps]]
|
[[steps]]
|
||||||
id = "test-dungeon"
|
id = "test-dungeon"
|
||||||
|
|
@ -31,56 +22,6 @@ runner = "rust-build"
|
||||||
required_environment = ["CARGO_HOME", "HOME"]
|
required_environment = ["CARGO_HOME", "HOME"]
|
||||||
argv = ["cargo", "build", "--locked", "--release", "-p", "ghostlight-dungeon", "--bin", "ghostlight-dungeon"]
|
argv = ["cargo", "build", "--locked", "--release", "-p", "ghostlight-dungeon", "--bin", "ghostlight-dungeon"]
|
||||||
|
|
||||||
[[steps]]
|
|
||||||
id = "install-web-dependencies"
|
|
||||||
phase = "prepare"
|
|
||||||
runner = "web-build"
|
|
||||||
required_environment = ["HOME", "NPM_CONFIG_CACHE"]
|
|
||||||
argv = ["npm", "--prefix", "web", "ci"]
|
|
||||||
|
|
||||||
[[steps]]
|
|
||||||
id = "test-web"
|
|
||||||
phase = "test"
|
|
||||||
runner = "web-build"
|
|
||||||
required_environment = ["HOME", "NPM_CONFIG_CACHE"]
|
|
||||||
argv = ["npm", "--prefix", "web", "test"]
|
|
||||||
|
|
||||||
[[steps]]
|
|
||||||
id = "build-web"
|
|
||||||
phase = "build"
|
|
||||||
runner = "web-build"
|
|
||||||
required_environment = ["HOME", "NPM_CONFIG_CACHE"]
|
|
||||||
argv = ["npm", "--prefix", "web", "run", "build"]
|
|
||||||
|
|
||||||
[[steps]]
|
|
||||||
id = "accept-real-persona-membrane"
|
|
||||||
phase = "acceptance"
|
|
||||||
runner = "rust-acceptance"
|
|
||||||
argv = [
|
|
||||||
"cargo",
|
|
||||||
"test",
|
|
||||||
"--locked",
|
|
||||||
"-p",
|
|
||||||
"ghostlight",
|
|
||||||
"--lib",
|
|
||||||
"controllers::tests::real_local_model_cognition_modes_commit_speech",
|
|
||||||
"--",
|
|
||||||
"--ignored",
|
|
||||||
"--exact",
|
|
||||||
]
|
|
||||||
required_environment = [
|
|
||||||
"CARGO_HOME",
|
|
||||||
"GHOSTLIGHT_ACCEPTANCE_PERSONA_PROSE_LOG",
|
|
||||||
"GHOSTLIGHT_ACCEPTANCE_RUNTIME_ID",
|
|
||||||
"GHOSTLIGHT_CONTROLLER_ELABORATOR_MODEL",
|
|
||||||
"GHOSTLIGHT_CONTROLLER_INTERPRETER_MODEL",
|
|
||||||
"GHOSTLIGHT_CONTROLLER_OPERATIONAL_MODEL",
|
|
||||||
"GHOSTLIGHT_CONTROLLER_PERSONA_MODEL",
|
|
||||||
"GHOSTLIGHT_CONTROLLER_PROJECTOR_MODEL",
|
|
||||||
"HOME",
|
|
||||||
"GHOSTLIGHT_LOCAL_ENDPOINT",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[artifacts]]
|
[[artifacts]]
|
||||||
id = "ghostlight-dungeon"
|
id = "ghostlight-dungeon"
|
||||||
source_kind = "runner-output"
|
source_kind = "runner-output"
|
||||||
|
|
@ -89,16 +30,8 @@ source = "target/release/ghostlight-dungeon"
|
||||||
destination = "ghostlight-dungeon"
|
destination = "ghostlight-dungeon"
|
||||||
executable = true
|
executable = true
|
||||||
|
|
||||||
[[artifacts]]
|
|
||||||
id = "web"
|
|
||||||
source_kind = "runner-output"
|
|
||||||
runner = "web-build"
|
|
||||||
source = "web/dist"
|
|
||||||
destination = "web"
|
|
||||||
|
|
||||||
[service]
|
[service]
|
||||||
executable_artifact = "ghostlight-dungeon"
|
executable_artifact = "ghostlight-dungeon"
|
||||||
required_adjacent_artifacts = ["web"]
|
|
||||||
arguments = [
|
arguments = [
|
||||||
{ kind = "literal", value = "--state-root" },
|
{ kind = "literal", value = "--state-root" },
|
||||||
{ kind = "binding", name = "state_root" },
|
{ kind = "binding", name = "state_root" },
|
||||||
|
|
@ -109,36 +42,40 @@ required_environment = [
|
||||||
"GAMECULT_IDUNN_CANDIDATE_BIND",
|
"GAMECULT_IDUNN_CANDIDATE_BIND",
|
||||||
"GAMECULT_IDUNN_PROCESS_WRITE_LEASE",
|
"GAMECULT_IDUNN_PROCESS_WRITE_LEASE",
|
||||||
"GAMECULT_IDUNN_RUNTIME_BUNDLE",
|
"GAMECULT_IDUNN_RUNTIME_BUNDLE",
|
||||||
|
"GHOSTLIGHT_CONNECTOR_ADDR",
|
||||||
|
"GHOSTLIGHT_CONNECTOR_KEY_FILE",
|
||||||
"GHOSTLIGHT_CONTROLLER_ELABORATOR_MODEL",
|
"GHOSTLIGHT_CONTROLLER_ELABORATOR_MODEL",
|
||||||
"GHOSTLIGHT_CONTROLLER_INTERPRETER_MODEL",
|
"GHOSTLIGHT_CONTROLLER_INTERPRETER_MODEL",
|
||||||
"GHOSTLIGHT_CONTROLLER_OPERATIONAL_MODEL",
|
"GHOSTLIGHT_CONTROLLER_OPERATIONAL_MODEL",
|
||||||
"GHOSTLIGHT_CONTROLLER_PERSONA_MODEL",
|
"GHOSTLIGHT_CONTROLLER_PERSONA_MODEL",
|
||||||
"GHOSTLIGHT_CONTROLLER_PROJECTOR_MODEL",
|
"GHOSTLIGHT_CONTROLLER_PROJECTOR_MODEL",
|
||||||
"GHOSTLIGHT_DISCORD_GUILD_ID",
|
|
||||||
"GHOSTLIGHT_DISCORD_ROLE_ID",
|
|
||||||
"GHOSTLIGHT_HEIMDALL_APP_SECRET_FILE",
|
"GHOSTLIGHT_HEIMDALL_APP_SECRET_FILE",
|
||||||
"GHOSTLIGHT_HEIMDALL_BASE_URL",
|
"GHOSTLIGHT_HEIMDALL_BASE_URL",
|
||||||
"GHOSTLIGHT_LOCAL_ENDPOINT",
|
|
||||||
"GHOSTLIGHT_LOCATED_SERVICE",
|
|
||||||
"GHOSTLIGHT_ODIN_RUDP",
|
"GHOSTLIGHT_ODIN_RUDP",
|
||||||
"GHOSTLIGHT_PLAY_MODEL",
|
"GHOSTLIGHT_PLAY_MODEL",
|
||||||
"GHOSTLIGHT_PUBLIC_APP_URL",
|
"GHOSTLIGHT_PUBLIC_APP_URL",
|
||||||
"GHOSTLIGHT_SERVICE_ID",
|
|
||||||
"GHOSTLIGHT_SESSION_WRAPPING_KEY_FILE",
|
"GHOSTLIGHT_SESSION_WRAPPING_KEY_FILE",
|
||||||
]
|
]
|
||||||
optional_environment = ["RUST_LOG"]
|
optional_environment = [
|
||||||
|
"GHOSTLIGHT_AUTH_PROVIDERS",
|
||||||
|
"GHOSTLIGHT_CONTROLLER_MAX_CONCURRENT",
|
||||||
|
"RUST_LOG",
|
||||||
|
]
|
||||||
|
|
||||||
[service.health]
|
[service.health]
|
||||||
contract = "ghostlight.cultnet-rudp-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]
|
[state]
|
||||||
schema_generation = "world-v3"
|
schema_generation = "dungeon-v1"
|
||||||
|
|
||||||
[[state.slots]]
|
[[state.slots]]
|
||||||
id = "world"
|
id = "catalog"
|
||||||
relative_path = "world.cc"
|
relative_path = "catalog.cc"
|
||||||
kind = "cultcache-file"
|
kind = "cultcache-file"
|
||||||
schema = "ghostlight.world_state.consumer.v6"
|
schema = "ghostlight.dungeon_catalog.v1"
|
||||||
writer = "process-bound-single-writer"
|
writer = "process-bound-single-writer"
|
||||||
recovery = "preserve"
|
recovery = "preserve"
|
||||||
startup = "create-or-open-after-write-lease"
|
startup = "create-or-open-after-write-lease"
|
||||||
|
|
@ -153,21 +90,21 @@ recovery = "preserve"
|
||||||
startup = "create-or-open-after-write-lease"
|
startup = "create-or-open-after-write-lease"
|
||||||
|
|
||||||
[[state.slots]]
|
[[state.slots]]
|
||||||
id = "controller-work"
|
id = "snapshots"
|
||||||
relative_path = "service/controller-work.cc"
|
relative_path = "snapshots"
|
||||||
kind = "cultcache-file"
|
kind = "external-file"
|
||||||
schema = "ghostlight.controller_work.v17"
|
schema = "ghostlight.vault_snapshot.v1"
|
||||||
writer = "process-bound-single-writer"
|
writer = "process-bound-single-writer"
|
||||||
recovery = "preserve"
|
recovery = "rebuildable"
|
||||||
startup = "create-or-open-after-write-lease"
|
startup = "create-or-open-after-write-lease"
|
||||||
|
|
||||||
[[state.slots]]
|
[[state.slots]]
|
||||||
id = "mesh-projection"
|
id = "timelines"
|
||||||
relative_path = "service/mesh-v2.cc"
|
relative_path = "timelines"
|
||||||
kind = "cultcache-file"
|
kind = "external-file"
|
||||||
schema = "gamecult.eve.surface.v1"
|
schema = "ghostlight.world_state.consumer.v6"
|
||||||
writer = "process-bound-single-writer"
|
writer = "process-bound-single-writer"
|
||||||
recovery = "rebuildable"
|
recovery = "preserve"
|
||||||
startup = "create-or-open-after-write-lease"
|
startup = "create-or-open-after-write-lease"
|
||||||
|
|
||||||
[[provides]]
|
[[provides]]
|
||||||
|
|
@ -175,11 +112,7 @@ capability = "ghostlight.world-service"
|
||||||
schema = "ghostlight.world_state.consumer.v6"
|
schema = "ghostlight.world_state.consumer.v6"
|
||||||
compatibility = "consumer-v6"
|
compatibility = "consumer-v6"
|
||||||
|
|
||||||
[[provides]]
|
# Heimdall is found through Odin at use, not declared as an Idunn dependency.
|
||||||
capability = "gamecult.eve.surface-provider"
|
|
||||||
schema = "gamecult.eve.surface.v1"
|
|
||||||
compatibility = "v1"
|
|
||||||
|
|
||||||
[[dependencies]]
|
[[dependencies]]
|
||||||
kind = "shared-infrastructure"
|
kind = "shared-infrastructure"
|
||||||
capability = "odin.verse-rendezvous"
|
capability = "odin.verse-rendezvous"
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,7 @@
|
||||||
# Ghostlight authority architecture
|
# Ghostlight authority architecture
|
||||||
|
|
||||||
|
> Status: the Dungeon daemon described here is parked at tag `parked/ghostlight-eve-surface` (2026-10-22); it is not on main.
|
||||||
|
|
||||||
## Status
|
## Status
|
||||||
|
|
||||||
This document is the adopted rebuild target for the Ghostlight runtime. It is
|
This document is the adopted rebuild target for the Ghostlight runtime. It is
|
||||||
|
|
@ -509,7 +511,9 @@ draws from it yet, and runtime readiness reads it. Changing it is a restart.
|
||||||
The five
|
The five
|
||||||
controller models are configuration too (`GHOSTLIGHT_CONTROLLER_PROJECTOR_MODEL`,
|
controller models are configuration too (`GHOSTLIGHT_CONTROLLER_PROJECTOR_MODEL`,
|
||||||
`_PERSONA_MODEL`, `_INTERPRETER_MODEL`, `_OPERATIONAL_MODEL`,
|
`_PERSONA_MODEL`, `_INTERPRETER_MODEL`, `_OPERATIONAL_MODEL`,
|
||||||
`_ELABORATOR_MODEL`), each with a default when absent.
|
`_ELABORATOR_MODEL`, and `GHOSTLIGHT_PLAY_MODEL` for the play table), each
|
||||||
|
required: the deployment names the exact model id and an unset lane refuses
|
||||||
|
startup.
|
||||||
|
|
||||||
The kernel commits one decision at a time through the mailbox. After each
|
The kernel commits one decision at a time through the mailbox. After each
|
||||||
commit the planner derives a fresh queue. Parallel inference may speculate on
|
commit the planner derives a fresh queue. Parallel inference may speculate on
|
||||||
|
|
@ -624,9 +628,11 @@ lane still uses. The real-model gate that exists today is the Idunn recipe's
|
||||||
runs `controllers::tests::real_local_model_cognition_modes_commit_speech`
|
runs `controllers::tests::real_local_model_cognition_modes_commit_speech`
|
||||||
against a real model; exercising a whole play turn against one is not gated
|
against a real model; exercising a whole play turn against one is not gated
|
||||||
by this contract.
|
by this contract.
|
||||||
`world.create`'s current payload is `world_create.v4`: title, brief, targets,
|
`world.begin` is the one route that makes a world. Its payload is
|
||||||
jurisdiction roots and lens weights are required, and Dungeon's create surface
|
`world_begin.v1`: title, brief and subject_label, nothing else; the route
|
||||||
offers uniform weights as its editable default. `world.seed` runs one
|
decides everything else a world is born with (no targets, no roots, no persona
|
||||||
|
or agent label, uniform lens weights) and `begin_plan` decides how far Begin
|
||||||
|
goes. `world.seed` runs one
|
||||||
`SeedRunner` session per invocation against a `VaultEvidenceSource`.
|
`SeedRunner` session per invocation against a `VaultEvidenceSource`.
|
||||||
|
|
||||||
Focused tests must prove:
|
Focused tests must prove:
|
||||||
|
|
|
||||||
|
|
@ -1,100 +0,0 @@
|
||||||
# Ghostlight Eve-native interface
|
|
||||||
|
|
||||||
## Objective
|
|
||||||
|
|
||||||
Ghostlight Dungeon exposes one logical surface, `ghostlight.play`, from the
|
|
||||||
provider `gamecult.ghostlight.dungeon` (`crates/ghostlight-dungeon/src/mesh.rs`).
|
|
||||||
Eve owns editable bindings, command invocation, receipts, plugin composition,
|
|
||||||
and browser lowering. Ghostlight owns world creation, seeding, activation, play,
|
|
||||||
and world admission; Heimdall owns authentication and entitlement decisions.
|
|
||||||
|
|
||||||
```text
|
|
||||||
Ghostlight projection (eve.rs)
|
|
||||||
-> EveBrowserProviderHost
|
|
||||||
-> canonical Eve lowering
|
|
||||||
-> gamecult.eve.command_invocation.v1
|
|
||||||
-> Ghostlight command ingress (runtime.rs) or Heimdall private command plane
|
|
||||||
-> gamecult.eve.command_result.v1
|
|
||||||
-> authoritative surface refresh
|
|
||||||
```
|
|
||||||
|
|
||||||
## Authority map
|
|
||||||
|
|
||||||
- Owner: the world kernel owns world changes (through `WorldMailbox`, `SeedPort`
|
|
||||||
and the play table), Heimdall owns OAuth attempts and claims, and Ghostlight's
|
|
||||||
app-session owner (`app_session.rs`) binds a verified Heimdall subject to a
|
|
||||||
local cookie.
|
|
||||||
- Inputs: the projector reads only the caller's app session, the world
|
|
||||||
snapshot, and the caller's play-turn view. Command ingress reads one canonical
|
|
||||||
Eve invocation and derives the principal server-side.
|
|
||||||
- Outputs: one `gamecult.eve.surface.v1` document and one
|
|
||||||
`gamecult.eve.command_receipt.v1` inside a command result.
|
|
||||||
- Derived state: browser drafts, focus, command status, and rendered HTML are
|
|
||||||
projections or local interaction state. None grants access or mutates
|
|
||||||
fiction.
|
|
||||||
- Forbidden writers: the browser, the Eve lowerer, the Heimdall plugin, and the
|
|
||||||
SSE stream cannot choose a principal or commit world state.
|
|
||||||
- Shared path: every operation resolves the authenticated account, then calls
|
|
||||||
the world mailbox, the seed port, or the play port.
|
|
||||||
SSE carries invalidation only and the host refetches the same surface.
|
|
||||||
|
|
||||||
## The surface
|
|
||||||
|
|
||||||
`GET /api/eve/surfaces/ghostlight.play` returns a different document by caller
|
|
||||||
and world phase (`anonymous_surface`, `authenticated_surface` in
|
|
||||||
`crates/ghostlight-dungeon/src/eve.rs`):
|
|
||||||
|
|
||||||
| Caller and world | Content | Operations |
|
|
||||||
|---|---|---|
|
|
||||||
| Anonymous | `heimdall.access_gate` | `heimdall.auth.begin`, `heimdall.auth.complete` |
|
|
||||||
| Authenticated, any world state | a `Sign out` button on every authenticated surface | `app.auth.logout` (`ghostlight.app_logout.v2`) |
|
|
||||||
| Authenticated, no world | the create form: title, brief, your name, optional Narrative persona and Operational agent labels, scale target, jurisdiction roots, lens weights | `world.create` (`ghostlight.world_create.v4`) |
|
|
||||||
| Draft world | world summary card; approve button for a required approver who has not approved; for the owner, the seed form and Seed card, and the activate button once every required approver has approved | `world.approve` (`ghostlight.world_approve.v0`), `world.seed` (`ghostlight.world_seed.v1`), `world.activate` (`ghostlight.world_activate.v0`) |
|
|
||||||
| Active world, owner | advance-time control and the Play card: narration, the open question, the refusal of the player's own act, one free-text control | `world.advance_time` (`ghostlight.world_advance_time.v0`), `world.play` (`ghostlight.world_play.v0`) |
|
|
||||||
|
|
||||||
`world.play` is the only human play action. The open question's identity rides
|
|
||||||
the play button's own action as an opaque token, never as an editable field.
|
|
||||||
`operation_schema` in `eve.rs` is the single table from operation id to schema.
|
|
||||||
|
|
||||||
## Editable values
|
|
||||||
|
|
||||||
Eve bindings are the input model. A component binds a typed value by stable
|
|
||||||
binding name, document identity, field path, value kind, and access mode.
|
|
||||||
Renderer-local composers use `local-draft`. An operation captures one or more
|
|
||||||
named binding values atomically.
|
|
||||||
|
|
||||||
The browser lowerer may use an HTML form for keyboard and accessibility
|
|
||||||
behavior. HTML form structure never enters Eve state or command payload
|
|
||||||
semantics. Accepted receipts may clear named drafts; rejection and stale
|
|
||||||
conflict preserve them. An omitted clear-binding list means clear the surface's
|
|
||||||
drafts; an explicit empty list means clear nothing. Ghostlight validates every
|
|
||||||
payload at ingress regardless of what the control advertises.
|
|
||||||
|
|
||||||
## Authentication membrane
|
|
||||||
|
|
||||||
Anonymous projection contains only `heimdall.access_gate`. Its begin and
|
|
||||||
complete operations cross Heimdall's encrypted, loopback-only CultNet boundary
|
|
||||||
(`heimdall.rs`). Ghostlight reads the redacted `heimdall:command-boundary`
|
|
||||||
record from Odin, validates it, and invokes the discovered route. Odin does not
|
|
||||||
proxy the command and never receives claims or completion payloads. The browser
|
|
||||||
retains only the opaque attempt handle (`web/src/heimdall-access-adapter.ts`).
|
|
||||||
Ghostlight redeems the completion, validates the access claim, and creates a
|
|
||||||
local HttpOnly session cookie (`ghostlight_session`).
|
|
||||||
|
|
||||||
Routine requests use local verified session state, persisted in
|
|
||||||
`app-sessions-v2.cc` (`app_session.rs`): the cookie hash, the Heimdall
|
|
||||||
session and `access_revision`, expiries, and a wrapped refresh claim.
|
|
||||||
`access_revision` is Heimdall's revocation epoch.
|
|
||||||
|
|
||||||
## Public boundary
|
|
||||||
|
|
||||||
- `GET /api/eve/provider`
|
|
||||||
- `GET /api/eve/surfaces/{surface_id}`
|
|
||||||
- `POST /api/eve/commands`
|
|
||||||
- `GET /api/eve/events`
|
|
||||||
- `GET /health`, a probe of the service's typed CultMesh health
|
|
||||||
- `POST /cultnet/snapshot` and `POST /cultnet/world-patch`, the loopback
|
|
||||||
CultNet doors (see `ghostlight-world-consumer-api.md` for the second)
|
|
||||||
|
|
||||||
Static assets in `web/` contain only the Eve provider host, the transport, the
|
|
||||||
Heimdall adapter, and the SSE invalidation hook.
|
|
||||||
|
|
@ -1,5 +1,7 @@
|
||||||
# Ghostlight Dungeon play agent (plan step 16)
|
# Ghostlight Dungeon play agent (plan step 16)
|
||||||
|
|
||||||
|
> Status: the Dungeon daemon described here is parked at tag `parked/ghostlight-eve-surface` (2026-10-22); it is not on main.
|
||||||
|
|
||||||
## Status
|
## Status
|
||||||
|
|
||||||
Target, adopted 2026-09-22. Not implemented. The means will be in
|
Target, adopted 2026-09-22. Not implemented. The means will be in
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,7 @@
|
||||||
# Ghostlight Dungeon Session Zero
|
# Ghostlight Dungeon Session Zero
|
||||||
|
|
||||||
|
> Status: the Dungeon daemon described here is parked at tag `parked/ghostlight-eve-surface` (2026-10-22); it is not on main.
|
||||||
|
|
||||||
Status: adopted direction, 2026-09-15. Not implemented. Its role as the
|
Status: adopted direction, 2026-09-15. Not implemented. Its role as the
|
||||||
playtest gate is superseded (operator, 2026-09-22) by the play agent,
|
playtest gate is superseded (operator, 2026-09-22) by the play agent,
|
||||||
`ghostlight-play-agent.md` (plan step 16). D1–D3 and the library passes
|
`ghostlight-play-agent.md` (plan step 16). D1–D3 and the library passes
|
||||||
|
|
|
||||||
|
|
@ -63,6 +63,11 @@ attributed proposal — is not part of this pass; see "Not in this pass" below.
|
||||||
|
|
||||||
## Transport
|
## Transport
|
||||||
|
|
||||||
|
Status: the HTTP door below lived in the Dungeon daemon's `api_router` and is
|
||||||
|
parked with it at tag `parked/ghostlight-eve-surface`; no process on main serves
|
||||||
|
it. `ghostlight::admit_document` and `encode_receipt` are the contract a host
|
||||||
|
serves.
|
||||||
|
|
||||||
`POST /cultnet/world-patch`, declared beside `/cultnet/snapshot` in
|
`POST /cultnet/world-patch`, declared beside `/cultnet/snapshot` in
|
||||||
`api_router` (`runtime.rs`). The handler gates loopback and content type
|
`api_router` (`runtime.rs`). The handler gates loopback and content type
|
||||||
(`application/msgpack`) exactly as the snapshot route does, then hands the
|
(`application/msgpack`) exactly as the snapshot route does, then hands the
|
||||||
|
|
|
||||||
|
|
@ -307,7 +307,7 @@ provider request is a distinct round (`interpreter_round`) with its own
|
||||||
content-addressed request id, so it cannot collide with the first lowering's
|
content-addressed request id, so it cannot collide with the first lowering's
|
||||||
request. State schema is `ghostlight.world_state.consumer.v6`, commit schema
|
request. State schema is `ghostlight.world_state.consumer.v6`, commit schema
|
||||||
`ghostlight.world_commit.consumer.v6`, controller work
|
`ghostlight.world_commit.consumer.v6`, controller work
|
||||||
`ghostlight.controller_work.v17`, Persona turn receipt
|
`ghostlight.controller_work.v18`, Persona turn receipt
|
||||||
`ghostlight.persona_turn_receipt.v3`; earlier stores and earlier rows are
|
`ghostlight.persona_turn_receipt.v3`; earlier stores and earlier rows are
|
||||||
refused. Ghostlight owns a conserved narrative ledger;
|
refused. Ghostlight owns a conserved narrative ledger;
|
||||||
Delvehold owns the economy (`delvehold-forced-ontology-integration.md`).
|
Delvehold owns the economy (`delvehold-forced-ontology-integration.md`).
|
||||||
|
|
@ -442,6 +442,8 @@ which noun a component is; it cares what it constrains.
|
||||||
| `Channel` | channel: reach set, controller (latency arrives with the clock, pass 7) | how facts travel; who can be silenced |
|
| `Channel` | channel: reach set, controller (latency arrives with the clock, pass 7) | how facts travel; who can be silenced |
|
||||||
| `Commitment` | subject → counterparty: kind (`Routine`, `Obligation`, `Goal`), due, period, statement | obligation with a clock; autonomous motion |
|
| `Commitment` | subject → counterparty: kind (`Routine`, `Obligation`, `Goal`), due, period, statement | obligation with a clock; autonomous motion |
|
||||||
| `Pressure` | source → target: magnitude | the causal boundary trigger |
|
| `Pressure` | source → target: magnitude | the causal boundary trigger |
|
||||||
|
| `Attitude` | holder → subject or trait: signed delta, cause, since, decay | how one subject regards another; sourced modifiers, never a stored opinion |
|
||||||
|
| `Trait` | subject → trait name: the facts that evidence it | what a prejudice may reach, once the holder knows one of them |
|
||||||
| `PersonaMaterial` | subject: values, voice, memories, reads | lived meaning; never authority |
|
| `PersonaMaterial` | subject: values, voice, memories, reads | lived meaning; never authority |
|
||||||
|
|
||||||
A `Fact` carries a `standing` (`FactStanding`, three variants): `Canonical`
|
A `Fact` carries a `standing` (`FactStanding`, three variants): `Canonical`
|
||||||
|
|
@ -451,6 +453,23 @@ belief. Deception is a subject asserting a claim while holding a contradicting
|
||||||
canonical fact; misread is a listener acquiring a claim the speaker did not
|
canonical fact; misread is a listener acquiring a claim the speaker did not
|
||||||
intend. Both are ordinary typed states, not narrator judgments.
|
intend. Both are ordinary typed states, not narrator judgments.
|
||||||
|
|
||||||
|
Attitude is a sum of sourced terms, in the manner of Crusader Kings opinion
|
||||||
|
modifiers. A modifier points at a subject or at a trait, carries a delta in
|
||||||
|
`-100..=100`, a cause (`Prejudice`, `Grievance` or `Favor` named for the command
|
||||||
|
that did the deed, or a `Rumour` over a fact), the clock at its last write, and an
|
||||||
|
optional fade. `attitude::opinion(holder, subject)` derives the regard on demand:
|
||||||
|
the direct modifiers, plus each trait modifier whose trait the subject carries
|
||||||
|
*and* whose evidencing fact the holder knows at `Believed` or better, summed and
|
||||||
|
clamped. A prejudice against outlanders does nothing to a stranger the holder
|
||||||
|
has not learned is one. `Trait` rows are declared by the world, never inferred.
|
||||||
|
The regard is projected to every reader from that one derivation: each subject's
|
||||||
|
snapshot, the table view the Dungeon Master reads, the Persona's own view, and
|
||||||
|
the narrator's account of who stands with the player. Only the reducer writes it,
|
||||||
|
through `AdjustAttitude` (a deed, or an affordance effect, whose regarded party is
|
||||||
|
fixed to the actor), `DeclareAttitude` (prejudice or rumour, authored without a
|
||||||
|
deed) and `DeclareTrait`. The three are additive on the state: a world with no
|
||||||
|
attitude serializes as it did before, so the state schema tag did not move.
|
||||||
|
|
||||||
Civic order is the `Authority` + `Selection` + `Redress` + `Custody` subgraph.
|
Civic order is the `Authority` + `Selection` + `Redress` + `Custody` subgraph.
|
||||||
It is not a prose manifest and needs no civic verdict. `Dependency` is the
|
It is not a prose manifest and needs no civic verdict. `Dependency` is the
|
||||||
crisis transmitter: it is what makes a failed pump in one realm a political
|
crisis transmitter: it is what makes a failed pump in one realm a political
|
||||||
|
|
@ -460,7 +479,7 @@ problem in another without anyone deciding that it should be.
|
||||||
|
|
||||||
This is the closed operation set. Every mutation the kernel applies is one of
|
This is the closed operation set. Every mutation the kernel applies is one of
|
||||||
these, and every model-facing tool is a projection of one of these. The type is
|
these, and every model-facing tool is a projection of one of these. The type is
|
||||||
`ComponentOp` in `crates/ghostlight/src/patch.rs`: 34 variants, named here by
|
`ComponentOp` in `crates/ghostlight/src/patch.rs`: 37 variants, named here by
|
||||||
the component they act on. Declarations are the six `Declaration` variants.
|
the component they act on. Declarations are the six `Declaration` variants.
|
||||||
|
|
||||||
```text
|
```text
|
||||||
|
|
@ -478,6 +497,7 @@ Knowledge AcquireKnowledge, Communicate, Witness, Forget
|
||||||
Channel SetReach, SetController
|
Channel SetReach, SetController
|
||||||
Commitment CreateCommitment, DischargeCommitment
|
Commitment CreateCommitment, DischargeCommitment
|
||||||
Pressure AdvancePressure, ReducePressure, ResolvePressure
|
Pressure AdvancePressure, ReducePressure, ResolvePressure
|
||||||
|
Attitude AdjustAttitude, DeclareAttitude, DeclareTrait
|
||||||
PersonaMaterial SetPersonaMaterial
|
PersonaMaterial SetPersonaMaterial
|
||||||
Retirement Retire
|
Retirement Retire
|
||||||
Affordance GrantAffordance, RevokeAffordance
|
Affordance GrantAffordance, RevokeAffordance
|
||||||
|
|
|
||||||
442
docs/targets/multiresolution-gestalt.md
Normal file
442
docs/targets/multiresolution-gestalt.md
Normal file
|
|
@ -0,0 +1,442 @@
|
||||||
|
# Multiresolution Gestalt: Target
|
||||||
|
|
||||||
|
Date: 2026-12-03. Campaign `ghostlight-verse` in the Weksa mind. Imagination pass
|
||||||
|
`gestalt-map`, session `weksa-self-20261202`. Base: Ghostlight `main` `93da896`;
|
||||||
|
the room cut builds on branch `ghostlight-verse/dungeon-npc-voice` at `d2c91ca`.
|
||||||
|
|
||||||
|
This page is the target shape and the authority map. Cut specs, questions,
|
||||||
|
research and ideas live in the mind; their ids are listed here so the page can
|
||||||
|
be read alone. Query them with
|
||||||
|
`huginn view <id>` or `huginn pass ghostlight-verse gestalt-map`.
|
||||||
|
|
||||||
|
## Why
|
||||||
|
|
||||||
|
Operator, 2026-12-03 (ruling `ghostlight-verse:ruling:multiresolution-gestalt`):
|
||||||
|
|
||||||
|
> Multiresolution Gestalt is core to the whole idea of Ghostlight, using a turn
|
||||||
|
> to simulate groups of people (and groups of groups, etc.) is how you can scale
|
||||||
|
> to massive worlds, as well as simulate massive worlds in parallel. For
|
||||||
|
> Ghostlight Dungeon, the DM should be dispatching Gestalt turns for the whole
|
||||||
|
> world, then the region, subregion, all the way down to the room the player is
|
||||||
|
> in (cut along the most semantically relevant lines, usually institutional
|
||||||
|
> rather than geographic) at varying rates, while also dispatching Elaborator
|
||||||
|
> agents to add depth to whatever the player happens to be looking at. Lots of
|
||||||
|
> knobs which it can use to fit the simulation's quality to the player's needs
|
||||||
|
> and budget.
|
||||||
|
|
||||||
|
Rulings this page stands on: `multiresolution-gestalt`, `dungeon-dm-owns-the-gears`,
|
||||||
|
`dungeon-models-dm-opus`, `dungeon-credit-burn`, `deru-play-profile`,
|
||||||
|
`aetheria-sim-first`, `two-ghostlight-consumers`, and the verse-sim rulings of
|
||||||
|
2026-10-10: `verse-sim-pipeline` (the verse runs multiresolution gestalts on a
|
||||||
|
schedule), `gestalt-machinery-port` (port the pre-rebuild machinery, do not
|
||||||
|
redesign it), `teardown-was-authority-sprawl` (port ideas onto the grammar
|
||||||
|
kernel, never ad hoc mutation rules), `gestalt-fission-auto` (splits are
|
||||||
|
admitted during runs), `grammar-scope-ruled`, `verse-cadence-ruled` (manual
|
||||||
|
under a hard token cap, then nightly under a monthly cap), `grouped-record-and-carry`,
|
||||||
|
`dungeon-vault-import-run-ahead` (elaborators run ahead of the player).
|
||||||
|
|
||||||
|
## What exists (Body at `93da896`)
|
||||||
|
|
||||||
|
- **The kernel is the only writer.** `WorldMailbox` admits a closed command
|
||||||
|
set; a subject acts only through its own opportunity (`ExerciseDecision`,
|
||||||
|
`DeclineDecision`, both of which stamp `last_opportunity_at`).
|
||||||
|
Subjects are `Person`, `Institution`, `Population` (`lib.rs:385`). Institution
|
||||||
|
structure is typed: offices with incumbents (`selection`, `lib.rs:921`),
|
||||||
|
authority grants over a subject or a place subtree (`authority`, `lib.rs:915`,
|
||||||
|
`patch.rs AuthorityTarget`). Places form a containment tree. There is no
|
||||||
|
population membership (`CausalBoundary::IndividuationRequired` is "declared,
|
||||||
|
never derived", `lib.rs:4358`).
|
||||||
|
- **The flat cover.** `cover.rs` partitions every active opportunity into
|
||||||
|
Singleton and Group cells under `CoverBudget {cells, constituent_cap,
|
||||||
|
urgency_slots}`, with a rotation window that guarantees every subject a
|
||||||
|
singleton turn within `ceil(N/R)` ticks. It is pure, derived and dropped each
|
||||||
|
tick; a Group cell is one inference over N labelled, never-unioned views,
|
||||||
|
each constituent submitting its own command (`controllers.rs run_group`).
|
||||||
|
The adjacency it reads is `agency_graph` (`lib.rs:3923`), exposed only on
|
||||||
|
`WorldMailbox` (`mailbox.rs:488`), never on a controller port.
|
||||||
|
- **The verse runner** (`verse/run.rs`, binary `ghostlight-verse`) advances a
|
||||||
|
world tick by tick under a token cap: open a tick document that freezes the
|
||||||
|
cover (`open_or_find`, `run.rs:1143`), run each cell through
|
||||||
|
`ControllerRunner::run_cell`, advance the clock once, checkpoint. Spend is
|
||||||
|
reserved before each call and settled after by `RecordingInferencePort`
|
||||||
|
(`verse/calls.rs:552`). It is the only world-scale scheduler today, and it is
|
||||||
|
one level deep: every faction every tick, at one resolution.
|
||||||
|
- **The Dungeon DM** (`ghostlight-dungeon/src/play.rs`, Opus) reads
|
||||||
|
`table_view`, `dispatch`es Personas, commits with authoring and actor tools,
|
||||||
|
and owns time through `advance_time`. Branch `dungeon-npc-voice` adds
|
||||||
|
`react`: one Persona-model call for the room's onlookers
|
||||||
|
(`PersonaLane::gestalt`), whose sections come back as drafts the DM commits
|
||||||
|
through each person's `__speak`. Nothing outside the DM's dispatches moves.
|
||||||
|
- **Run-ahead** (`run_ahead.rs`) starts a bounded elaboration sweep after each
|
||||||
|
closed turn (`api.rs:443`), sized by `Scale` session and permit counts
|
||||||
|
(`begin.rs:39`). Its claim order is jurisdiction order, then derivation order
|
||||||
|
(`elaboration.rs:963`): it does not know where the player is or looks.
|
||||||
|
- **The pre-rebuild design** (`docs/articles/multiresolution-gestalts.md`, tag
|
||||||
|
`parked/ghostlight-pre-rebuild`
|
||||||
|
`docs/architecture/ghostlight-multiresolution-agency.md`) had the agency
|
||||||
|
graph, a budgeted connected cover, cohesive versus arena cells, detail debt,
|
||||||
|
approval-gated fission and population baselines with member deltas. The
|
||||||
|
cover, arena cells and detail debt (as the rotation window) are ported.
|
||||||
|
The hierarchy, rates, focus and membership are not.
|
||||||
|
|
||||||
|
## Prior art that shaped this
|
||||||
|
|
||||||
|
Research notes of pass `gestalt-map` (`ghostlight-verse:research:gestalt-map.*`):
|
||||||
|
|
||||||
|
- `brom-lod-membrane`. IVE (Šerý, Poch, Šafrata, Brom 2006; Brom, Šerý, Poch,
|
||||||
|
IVA 2007): detail is an elastic membrane cut through a location tree; an
|
||||||
|
important object presses it down; LOD influence between neighbours makes a
|
||||||
|
crater, not a hole, around the player; locations expand eagerly and shrink
|
||||||
|
lazily in a garbage-collection pass; a process above the membrane runs
|
||||||
|
atomically and is partially evaluated when detail drops; one dedicated
|
||||||
|
"genius" can drive several actors at once. This is the shape of focus,
|
||||||
|
promotion, demotion and hysteresis below.
|
||||||
|
- `navarro-mesoscopic`. Navarro, Corruble, Flacher, Zucker (AAMAS 2013):
|
||||||
|
aggregate the minds, keep the bodies; partial disaggregation of only the
|
||||||
|
members something interacts with. Full macro aggregation lost emergent
|
||||||
|
micro phenomena and consistency fell. A Ghostlight Group cell is already
|
||||||
|
mesoscopic: one decision call, every member's state stays its own.
|
||||||
|
- `mrm-aggregation-failures`. The multiresolution-modelling literature's known
|
||||||
|
failures at level boundaries: chain disaggregation, transition latency,
|
||||||
|
thrashing, and mapping inconsistency between representations; MRE keeps
|
||||||
|
every representation with mapping functions (Reynolds, Natrajan, Srinivasan
|
||||||
|
1997). Ghostlight avoids the class by keeping one representation.
|
||||||
|
- `holonic-mas`. Holons (Gerber, Siekmann, Vierke 1999; Fischer, Schillo,
|
||||||
|
Siekmann 2003; Gaud et al. 2008): a group appears outward as one agent whose
|
||||||
|
head speaks for members that gave up part of their autonomy; recursive;
|
||||||
|
reorganised at run time. Ghostlight's head is an institution subject with
|
||||||
|
its own controller, and that is why the cut goes along institutions first.
|
||||||
|
- `dwarf-fortress-world-vs-site`. Dwarf Fortress runs world history coarsely
|
||||||
|
and keeps it running during play; off-site events reach the active site only
|
||||||
|
through in-world channels (a liaison, invaders who physically travel). The
|
||||||
|
Dungeon's equivalent: off-screen waves write kernel acts, and the player
|
||||||
|
learns of them only through knowledge and travel.
|
||||||
|
- `paradox-pops`. Victoria 3 aggregates people into pops keyed by profession,
|
||||||
|
culture, religion, workplace and state, and cost scales with the number of
|
||||||
|
pops, not of people; interest groups are fractions of pops. Aggregation keys
|
||||||
|
are typed attributes, not a model's judgement.
|
||||||
|
- `sunshine-hill-alibi`. Alibi generation (Sunshine-Hill and Badler, AIIDE
|
||||||
|
2010; dissertation 2011): fill in an agent's goals and history only when
|
||||||
|
inspected, consistent with what was already observed. That is what an
|
||||||
|
elaborator does when the player opens a node nobody authored.
|
||||||
|
- `ghostlight-pre-rebuild-gestalt` and `ghostlight-flat-cover-today`: the repo
|
||||||
|
facts above.
|
||||||
|
|
||||||
|
## Vocabulary
|
||||||
|
|
||||||
|
- **Node.** A vertex of the gestalt hierarchy: `World` (root), an
|
||||||
|
`Institution` node anchored at an institution subject, a `Place` node
|
||||||
|
anchored at a place entity, or a `Subject` leaf.
|
||||||
|
- **Voice.** A subject that acts in a node's turn. An open node's voices are
|
||||||
|
its children's anchors and its loose subjects; a closed institution node's
|
||||||
|
only voice is the institution itself.
|
||||||
|
- **Gestalt turn (node turn).** One wave's work for one node: its voices,
|
||||||
|
partitioned into cells by `derive_cover` when they exceed the constituent
|
||||||
|
cap, each cell one inference through the existing lanes.
|
||||||
|
- **Wave.** The set of node turns one planning pass chose, frozen with
|
||||||
|
deterministic ids before any inference.
|
||||||
|
- **Focus.** The places and nodes detail is pressed down around: the player's
|
||||||
|
place always, plus what the DM names. Distance is counted in hierarchy steps
|
||||||
|
from the focus.
|
||||||
|
- **Rate.** A period in fictional minutes per distance band. A node is due
|
||||||
|
when its most neglected voice was last attended at least one period ago.
|
||||||
|
- **Room.** The player's place and the subjects positioned in it. The one
|
||||||
|
level that is always geographic, because presence is physical.
|
||||||
|
|
||||||
|
## Invariants
|
||||||
|
|
||||||
|
- **G1 `kernel-only-writer`.** Every effect of a turn at any level reaches the
|
||||||
|
world as an ordinary submission by an exact subject (`ExerciseDecision`,
|
||||||
|
`DeclineDecision`) or a confined patch through the mailbox (elaborator, play
|
||||||
|
table). The hierarchy, waves, knobs, focus and ledgers never enter
|
||||||
|
`WorldState`, a `CommandEnvelope` or a scope digest.
|
||||||
|
- **G2 `one-representation`** (a group turn is legible at the finer level).
|
||||||
|
Ghostlight aggregates attention, never state. A coarse turn acts only through
|
||||||
|
subjects that exist, so the finer level reads exactly what it wrote. Opening
|
||||||
|
a node writes nothing and needs no disaggregation; closing one writes
|
||||||
|
nothing and discards nothing. A group turn's uncommitted prose is not canon,
|
||||||
|
as a Persona's draft is not.
|
||||||
|
- **G3 `bounded-and-reported`.** Every model call of every level reserves its
|
||||||
|
bound in a ledger before it is made and is settled and reported after, by
|
||||||
|
lane (room, wave, elaboration), node and distance. A call that could pass its
|
||||||
|
allowance is not made; the node is reported deferred, never dropped silently.
|
||||||
|
- **G4 `institutions-first`.** The hierarchy is derived from world state, and
|
||||||
|
a subject's home is decided by institutional ties before places: office
|
||||||
|
incumbency, then authority over the subject, then authority over a place
|
||||||
|
subtree containing it, then place containment, then the root.
|
||||||
|
- **G5 `one-planner`.** The Dungeon and the verse plan waves with one pure
|
||||||
|
function over (hierarchy, opportunities, knobs, focus, wave ordinal). The
|
||||||
|
drivers differ only in who sets the knobs, when a wave runs, and who owns
|
||||||
|
time.
|
||||||
|
- **G6 `no-starvation`.** Every voice of every due node is attended within its
|
||||||
|
rate period times the rotation bound of `derive_cover`; deferral is visible
|
||||||
|
in the wave report.
|
||||||
|
- **G7 `cohesion-needs-authority`.** Only an institution subject speaks for
|
||||||
|
others, through its own affordances. Every other grouping is an arena in
|
||||||
|
which each act names its exact subject (the grouped lane's per-handle rule).
|
||||||
|
- **G8 `replayable-waves`.** Hierarchy, wave and command ids are pure over
|
||||||
|
world state, knobs and the wave ordinal, so a resumed wave re-submits the
|
||||||
|
same ids and the kernel answers with the original receipts.
|
||||||
|
|
||||||
|
## Identity, lifecycle and authority
|
||||||
|
|
||||||
|
| Thing | Named by | Life over time | Who decides |
|
||||||
|
|---|---|---|---|
|
||||||
|
| Node (resolution level / group node) | `NodeId`: sha256 over a fixed namespace, the world id and the anchor (`World`, `Institution(SubjectId)`, `Place(EntityId)`, `Subject(SubjectId)`) | Derived on every read from the current world state; exists while its anchor exists and has at least one live descendant voice; never stored. A world change moves a subject to another parent on the next read, with no migration step | `derive_hierarchy` (kernel-private, beside `agency_graph`), exposed only on `WorldMailbox::hierarchy` |
|
||||||
|
| Node state open/closed | (node, wave) | Decided per wave by the planner from focus and depth; held only in the frozen wave | The planner, from the driver's knobs |
|
||||||
|
| Gestalt turn (node turn) | `(world, node, wave ordinal)`; its cells' ids from `cover.rs` with the wave ordinal in place of the tick | Frozen in the wave document before the first inference; each cell runs through `ControllerRunner::run_cell`, resumes from its controller-work row, ends committed, declined, refused or deferred | Cells decide what voices do; the kernel admits; the wave runner owns order and checkpoints and nothing else |
|
||||||
|
| Wave | Verse: the tick ordinal (clock advances). Dungeon: `(timeline, closed turn sequence)` | Opened (frozen) once, run, closed once; an open wave is finished as frozen by the next run | The driver opens and closes it; the planner chooses its content |
|
||||||
|
| Room turn | The DM's `react` call slot in the play turn, as `dispatch` today | Inside one play turn, recorded and resumed by the play turn store | The DM's judgement (`dungeon-dm-owns-the-gears`) |
|
||||||
|
| Level rate | Distance band (0 = the focus's own node, 1, 2, ..., and `rest`) mapped to a period in fictional minutes | Standing value in the knobs; changed by the DM tool or the verse run config; takes effect at the next wave | Dungeon: the DM. Verse: the operator's run config |
|
||||||
|
| DM knobs (rates, depth, budget, focus) | One `GestaltKnobs` document per Dungeon timeline; the verse's `VerseRunConfig` | Persisted per timeline, survives reload; default at Begin; each wave records the knob values it was planned under | The DM through one `tune` tool; the player only by asking the DM; never the kernel |
|
||||||
|
| Focus entry | Place or node id, with a lease in fictional minutes | Added by the DM or implied by the player's place; the player's place never expires; others expire at lease end (lazy shrink) | The DM; expiry by the planner reading `now` |
|
||||||
|
| Promotion (opening a node) | The node in a wave that plans it open | Happens when the focus comes within `depth` of it, or the DM forces it, or its detail debt makes it due; writes nothing | The planner |
|
||||||
|
| Demotion (closing a node) | The node in a wave that plans it closed | Only after the lease of the focus that opened it ends and the next wave plans it closed (shrink lazily); writes nothing | The planner |
|
||||||
|
| Spend ledger window | Verse: the run. Dungeon: the post-turn window | Reserve before each call, settle after, report by lane, node and distance | The recording port (`RecordingInferencePort` core) |
|
||||||
|
|
||||||
|
## Authority map
|
||||||
|
|
||||||
|
### Who owns the hierarchy
|
||||||
|
|
||||||
|
- **Owner.** `derive_hierarchy(&WorldState) -> Hierarchy`, a pure kernel-private
|
||||||
|
function beside `agency_graph`, reached only through `WorldMailbox::hierarchy`.
|
||||||
|
- **Inputs.** `selection` (offices, incumbents), `authority` grants over
|
||||||
|
subjects and place subtrees, `positions`, place containment,
|
||||||
|
`controller_assignments` (only subjects with a non-Human controller are
|
||||||
|
voices; the player is placed but never a voice).
|
||||||
|
- **Outputs.** A tree: `World` root; institution nodes; place nodes only where
|
||||||
|
some live subject has no institutional home; subject leaves. Each node lists
|
||||||
|
its children, its anchor voice (if any) and its loose subjects. Also the
|
||||||
|
focus path of any place: the chain of nodes that govern it.
|
||||||
|
- **Home-parent rule.** A subject's parent is the first that exists of: the
|
||||||
|
institution in which it holds an office (several: the one with the fewest
|
||||||
|
live members, then the lowest id); the institution holding an authority grant
|
||||||
|
over it; the innermost institution holding a grant over a place subtree that
|
||||||
|
contains its position; the innermost place node containing its position; the
|
||||||
|
root. An institution's own parent follows the same rule. A cycle is broken
|
||||||
|
at its lowest id, which then hangs from the root. Other ties stay visible as
|
||||||
|
context, not as second parents (question `gestalt-multi-affiliation`).
|
||||||
|
- **Derived state.** The whole hierarchy, node ids, focus paths. Nothing is
|
||||||
|
stored. An elaborator, the DM or a Persona changes the hierarchy only by
|
||||||
|
changing the world through ordinary commands (granting an office, a grant,
|
||||||
|
a move).
|
||||||
|
- **Forbidden writers.** No hierarchy document, no declared tree, no cache that
|
||||||
|
outlives one read, no model output.
|
||||||
|
- **Shared paths.** The Dungeon wave, the verse tick, the DM's view of what is
|
||||||
|
due and the elaborator's focus all read the same `hierarchy()`.
|
||||||
|
|
||||||
|
### Who schedules
|
||||||
|
|
||||||
|
- **Owner.** One pure planner, `plan_wave(world, ordinal, &Hierarchy,
|
||||||
|
&[DecisionOpportunity], &GestaltKnobs, &Focus, now) -> Wave`. It opens nodes
|
||||||
|
along each focus path up to `depth`, closes everything else, takes the due
|
||||||
|
nodes by rate, orders them nearest-focus first then most overdue, partitions
|
||||||
|
each node's voices into cells with `derive_cover` (the agency graph
|
||||||
|
restricted to those voices) and cuts the list at the knobs' turn bound.
|
||||||
|
- **Two drivers, one planner.**
|
||||||
|
- *Dungeon.* The DM owns the gears inside a turn: the room is its `react`
|
||||||
|
call. Above the room, the DM sets standing knobs and focus with `tune`;
|
||||||
|
after each closed play turn the Dungeon plans one wave and runs it, while
|
||||||
|
the player reads the narration; the DM may force a node now with
|
||||||
|
`run_world`. Time stays the DM's (`advance_time`); a wave never advances
|
||||||
|
the clock. (Question `gestalt-dungeon-trigger` asks whether the DM
|
||||||
|
should instead call every wave itself.)
|
||||||
|
- *Verse.* A tick plans a wave with no focus (or the operator's), runs it,
|
||||||
|
and advances the clock by the frozen span. The tick document freezes the
|
||||||
|
wave instead of the flat cover.
|
||||||
|
- **Derived state.** `derive_cover` is no longer the scheduler; it is the
|
||||||
|
within-node cell partition. `Resolution::{Detail, Coarse}` stays a derived
|
||||||
|
label. Due-ness is derived from kernel `last_opportunity_at`; no second
|
||||||
|
schedule store exists.
|
||||||
|
- **Forbidden writers.** No background timer, no wall clock, no code path that
|
||||||
|
runs a world wave the knobs did not plan. Run-ahead stops choosing its own
|
||||||
|
claim order (below).
|
||||||
|
|
||||||
|
### How Gestalt and Elaborator turns share the budget
|
||||||
|
|
||||||
|
- **Owner.** One ledger per window: the reserve-before-call, settle-after core
|
||||||
|
of `RecordingInferencePort`, with every call record tagged by lane
|
||||||
|
(`room`, `wave`, `elaboration`), node and distance.
|
||||||
|
- **Allowances.** The knobs split a window's token budget between the `wave`
|
||||||
|
and `elaboration` lanes. The room lane is the DM's play turn, bounded by its
|
||||||
|
round budget and the per-call output cap, and is reported but never starved
|
||||||
|
by background lanes: background lanes run after the turn closes.
|
||||||
|
- **Elaboration focus.** The elaborator's sweep takes the focus as its first
|
||||||
|
claim key: boundaries and deficits at focus places first, then the
|
||||||
|
current order. A place is at focus when it is a focus place, inside one, or
|
||||||
|
one open route from one (read either way); a boundary's place is its
|
||||||
|
destination's, or the position of the subject it names; a deficit's is its
|
||||||
|
jurisdiction root; the uncovered residual is nowhere. The partition is stable,
|
||||||
|
so an empty focus is today's order. Focus is also the outer key of fair
|
||||||
|
claims: in-focus demand before the rest, and inside each band an untried
|
||||||
|
entry before a tried one. It answers "what is the player looking at" with
|
||||||
|
structure, where waves answer it with action.
|
||||||
|
- **Demotions.** `Scale::sweep_sessions` and `sweep_permits` stop deciding
|
||||||
|
how much elaboration happens; the elaboration allowance does, and permits
|
||||||
|
stay a concurrency bound. The verse's `COVER` constant becomes a knob value.
|
||||||
|
The verse's run token cap is the wave lane's allowance.
|
||||||
|
|
||||||
|
Landed (cut `gestalt-ledger`, on Ghostlight `main` `1419b3b`): call records are
|
||||||
|
`ghostlight.verse_provider_call.v2` (lane and request id) and a run's ledger
|
||||||
|
`ghostlight.verse_run_ledger.v2` (allowances and spend by lane). A call that
|
||||||
|
could pass its lane's allowance is refused `budget_exhausted` in `reserve`,
|
||||||
|
beside the run cap, before the provider is called; the play agent has no lane
|
||||||
|
and is refused at the port. `WaveSpend::of` joins records to a frozen wave by
|
||||||
|
the command id a request id begins with, so node spend is a join and
|
||||||
|
`NodeOutcome.spent` is gone. The verse tick is `ghostlight.verse_tick.v3` and
|
||||||
|
records what the plan deferred; the tick report lists deferred nodes with why
|
||||||
|
(not due, over the node-turn bound, past the allowance). The Dungeon's run-ahead
|
||||||
|
spends in `window-<world revision>` of the timeline's `calls.cc`, under the
|
||||||
|
allowances of the timeline's knobs (below).
|
||||||
|
|
||||||
|
### Deletion line
|
||||||
|
|
||||||
|
Before the hierarchy lands nothing is deleted. In order: `react`'s mandatory
|
||||||
|
subject list becomes an override (room derived); the verse's one-line
|
||||||
|
`derive_cover` call over all opportunities is replaced by `plan_wave`; the
|
||||||
|
Dungeon's unfocused post-turn sweep is replaced by the focused, allowance-bounded
|
||||||
|
one; `Scale`'s sweep counts are deleted when the allowance lands.
|
||||||
|
|
||||||
|
## The shape in one walk
|
||||||
|
|
||||||
|
Deru stands in the Ironmarket tap-room. He insults the guild factor.
|
||||||
|
|
||||||
|
1. Room. The DM `dispatch`es the factor and `react`s the room: one call, every
|
||||||
|
onlooker in the tap-room from their own slice. The DM commits what is said.
|
||||||
|
2. The turn closes. The Dungeon plans a wave with focus = the tap-room.
|
||||||
|
The focus path is tap-room → Ironmarket Guild (it holds the market district's
|
||||||
|
grant) → City Council → Crown → World. With depth 2, the Guild and the
|
||||||
|
Council are open: the guild's officers and the watch captain act in their
|
||||||
|
own cells; the Crown is closed and acts as one voice at its slower rate
|
||||||
|
when due; the rest of the world turns as closed institution voices only when
|
||||||
|
their band's period has passed.
|
||||||
|
3. Every act goes through the kernel. The factor's grudge is a commitment and a
|
||||||
|
pressure; the guild's order to its enforcers is the guild's act, heard by its
|
||||||
|
audience.
|
||||||
|
4. The elaborator spends its allowance on boundaries under the tap-room and its
|
||||||
|
exits first.
|
||||||
|
5. Next turn, the DM's view shows what moved off-screen and what is due. When
|
||||||
|
Deru walks into the guild hall, its officers already have their own state:
|
||||||
|
nothing to disaggregate.
|
||||||
|
|
||||||
|
## How the verse runner fits
|
||||||
|
|
||||||
|
The verse runner is the unattended driver of the same planner. It keeps its
|
||||||
|
tick document, its token cap, its resume rules and its clock advance; only
|
||||||
|
the content it freezes changes, from one flat cover to one planned wave. With no
|
||||||
|
focus and a depth knob, a verse tick turns the world's institutions as closed
|
||||||
|
voices at their band rates, and `derive_cover` still bounds each node's cells.
|
||||||
|
Ruling `verse-cadence-ruled` (manual under a hard cap, then nightly) is its
|
||||||
|
trigger; the Dungeon's closed turn is the other.
|
||||||
|
|
||||||
|
Landed (cut `gestalt-wave-driver`): the tick document is
|
||||||
|
`ghostlight.verse_tick.v2`, each frozen cell carries its node and distance, and
|
||||||
|
the tick records the knobs. The operator sets them with
|
||||||
|
`ghostlight-verse run --depth N --band DIST=MINUTES` (repeatable); the default
|
||||||
|
is depth 1 and one band at the tick span, which plans the flat cover's shape.
|
||||||
|
`run_frozen_cells` in `wave.rs` runs the frozen cells for any driver; the clock
|
||||||
|
advance stays in the verse driver.
|
||||||
|
|
||||||
|
Landed (cut `dungeon-world-waves`, branch `ghostlight-verse/dungeon-world-waves`
|
||||||
|
from Ghostlight `main` `ab290dc`): after each closed play turn the Dungeon runs
|
||||||
|
`run_waves` (`waves.rs`) under the sweep lock, before run-ahead. It finishes any
|
||||||
|
wave left open, then plans one wave with `plan_wave` over the derived hierarchy
|
||||||
|
with the player's place as focus and constant knobs (bands 60, 360, 1440 and
|
||||||
|
10080 minutes, depth 2, four node turns, cover 4/6/1). The wave is frozen under
|
||||||
|
the closed turn's log `seq` in the timeline's `waves.cc`
|
||||||
|
(`ghostlight.dungeon_wave.v1`) before its first call, runs through
|
||||||
|
`run_frozen_cells` on a runner over the window port, and closes once with a
|
||||||
|
report. It spends in `window-<revision it opened at>`, so a resumed wave
|
||||||
|
reopens its own ledger and re-submits its own command ids. A voice the world
|
||||||
|
has never given an opportunity counts as attended at the clock's origin, so
|
||||||
|
nothing is due until a band's period has passed and a wave never turns a world
|
||||||
|
whose clock has not moved. The clock stays the DM's. The DM's next opening view
|
||||||
|
carries the closed waves it has not seen: acts by node, then nodes due but not
|
||||||
|
run. A wave that stops with a cell unfinished stays open and is finished at the
|
||||||
|
timeline's next closed turn. (That is the wave as `dungeon-world-waves`
|
||||||
|
landed it; the knobs, the document version and the room rule changed with
|
||||||
|
`dm-gestalt-knobs`, below.)
|
||||||
|
|
||||||
|
Landed (cut `dm-gestalt-knobs`, branch `ghostlight-verse/dm-gestalt-knobs` from
|
||||||
|
Ghostlight `main` `d3b0e20`): the knobs are one document per timeline,
|
||||||
|
`ghostlight.dungeon_gestalt_knobs.v1` in `gestalt-knobs.cc` (`knobs.rs`),
|
||||||
|
written with a Begin's defaults when a timeline opens without one: bands 60,
|
||||||
|
360, 1440 and 10080 minutes, depth 2, four node turns, cover 4/6/1, and a wave
|
||||||
|
and an elaboration allowance of 200000 tokens a window (sized to the retired
|
||||||
|
four-session sweep; no cost is measured yet). `default_knobs`,
|
||||||
|
`Scale::sweep_sessions`, `Scale::window` and their environment variables are
|
||||||
|
deleted; `Scale::sweep_permits` stays as the concurrency bound. The wave, the
|
||||||
|
run-ahead sweep and the opening view read the document, and each wave
|
||||||
|
(`ghostlight.dungeon_wave.v2`) records the knobs, allowances, DM focus and
|
||||||
|
forced nodes it planned under; the window it runs in follows the knobs as they
|
||||||
|
stand.
|
||||||
|
|
||||||
|
The DM turns them with two tools. `tune` sets bands (1 to 8 periods of 1 to
|
||||||
|
525600 minutes), depth (1 to 8), `max_node_turns` (1 to 32), the two lane
|
||||||
|
allowances (0 to 5000000 tokens), and adds or removes focus entries, each a
|
||||||
|
place or an institution by the id `table_view` prints, with a lease in
|
||||||
|
fictional minutes. A value outside its bound refuses the whole call, quoting
|
||||||
|
the value. A lease is an end minute: past it the entry is not focus, and the
|
||||||
|
next `tune` drops it. The player's own place is derived, never stored.
|
||||||
|
`run_world` names places or institutions; the next post-turn wave opens them
|
||||||
|
like focus nodes, treats them as due whatever their band and runs them ahead of
|
||||||
|
every other node, within the wave allowance (a node past it is reported
|
||||||
|
waiting); that wave takes the request whether or not it ran. The opening view
|
||||||
|
prints the knobs, the focus path by label, the DM's leases and queued nodes,
|
||||||
|
and the average tokens a node turn has cost in each band from the closed waves.
|
||||||
|
The knobs are the authority over a window's limits: a window already open at
|
||||||
|
the current revision follows a tuned allowance (`open_following`), keeps its
|
||||||
|
spend, and a lane held above a lowered allowance is exhausted, not an error.
|
||||||
|
A `run_world` target with no one to take a turn is frozen into its wave and the
|
||||||
|
next view says "nothing stirred" at it.
|
||||||
|
|
||||||
|
A wave gives no turn to a subject standing in the player's place: the room is
|
||||||
|
the DM's `react`. The DM's focus on an institution opens its node for waves;
|
||||||
|
the elaborator's claim order reads only the places.
|
||||||
|
|
||||||
|
## Cut sequence
|
||||||
|
|
||||||
|
Each cut is one `cut_spec` in the mind, `ghostlight-verse:cut_spec:cut-<cut>.r1`,
|
||||||
|
sized for one Sonnet Hands. Rejected alternatives are the ideas
|
||||||
|
`ghostlight-verse:idea:gestalt-map.*`, each with its Recorded resolution.
|
||||||
|
|
||||||
|
1. `gestalt-room`: `react` becomes the room-level Gestalt turn: the room
|
||||||
|
derived from the player's place, sections keyed by handle, non-Persona
|
||||||
|
subjects routed instead of failing the call. On `dungeon-npc-voice`.
|
||||||
|
2. `gestalt-hierarchy`: `derive_hierarchy` and `WorldMailbox::hierarchy`.
|
||||||
|
3. `gestalt-planner`: `plan_wave`, `GestaltKnobs`, `Focus`, due-ness. Depends on 2.
|
||||||
|
4. `gestalt-wave-driver`: the shared wave runner; verse ticks freeze planned
|
||||||
|
waves. Depends on 3.
|
||||||
|
5. `gestalt-ledger`: lane, node and distance on call records; lane
|
||||||
|
allowances; the Dungeon gets a ledger. Depends on 4.
|
||||||
|
6. `elaboration-focus`: the sweep's focus-first claim order; Dungeon
|
||||||
|
run-ahead spends the elaboration allowance on the player's focus. Depends on 5.
|
||||||
|
7. `dungeon-world-waves`: a wave after each closed play turn; off-screen acts
|
||||||
|
and due nodes in the DM's view. Depends on 1, 4, 5.
|
||||||
|
8. `dm-gestalt-knobs`: the DM's `tune` and `run_world` tools; knobs persisted
|
||||||
|
per timeline; focus leases. Depends on 6, 7.
|
||||||
|
9. `closed-voice-digest`: a closed institution's view carries a capped digest
|
||||||
|
of its folded members' salient state. Depends on 3.
|
||||||
|
|
||||||
|
## Questions
|
||||||
|
|
||||||
|
- `ghostlight-verse:question:gestalt-hierarchy-owner`: derived, declared or
|
||||||
|
model-proposed hierarchy. Recommended: derived.
|
||||||
|
- `ghostlight-verse:question:gestalt-multi-affiliation`: one home parent or a
|
||||||
|
voice in every institution. Recommended: one home parent.
|
||||||
|
- `ghostlight-verse:question:gestalt-dungeon-trigger`: the DM calls every wave,
|
||||||
|
or sets knobs that a post-turn step runs. Recommended: standing knobs.
|
||||||
|
- `ghostlight-verse:question:gestalt-rate-clock`: rates in fictional minutes or
|
||||||
|
in play turns. Recommended: fictional minutes.
|
||||||
|
- `ghostlight-verse:question:gestalt-population-membership`: port population
|
||||||
|
baselines and member deltas now, or individuate through elaborators.
|
||||||
|
Recommended: defer.
|
||||||
|
|
||||||
|
## Not in scope
|
||||||
|
|
||||||
|
- Population membership, baselines, member deltas and fission (the question
|
||||||
|
above holds it; ruling `gestalt-fission-auto` governs fission when it comes).
|
||||||
|
- A model-chosen cut per wave (the old six-axis demand model).
|
||||||
|
- Eve or any play-surface change beyond the DM's own view.
|
||||||
|
- Cost tuning: allowances and rates are measured in the burn
|
||||||
|
(`dungeon-credit-burn`), not designed here.
|
||||||
|
|
@ -2,25 +2,22 @@
|
||||||
|
|
||||||
This is a pointer. It does not carry open work; the Eureka mind does.
|
This is a pointer. It does not carry open work; the Eureka mind does.
|
||||||
|
|
||||||
## What runs
|
## What exists
|
||||||
|
|
||||||
Ghostlight Dungeon runs on Yggdrasil under Idunn at
|
`crates/ghostlight-dungeon` and `deployment/idunn/recipe.toml` are live on `main`
|
||||||
`https://yggdrasil.gamecult.org/ghostlight/` (runtime `ghostlight-yggdrasil`,
|
for the Dungeon playtest (brake release admitted in
|
||||||
target `ghostlight`, ref `main`, state root `/var/lib/gamecult/ghostlight-world-v2`).
|
`ghostlight-verse:ruling:ghostlight-brake-release-granted`). The earlier Eve
|
||||||
`/health` names the commit it serves (`crates/ghostlight-dungeon/src/runtime.rs`).
|
surface remains at tag `parked/ghostlight-eve-surface` as history.
|
||||||
The binary is `ghostlight-dungeon`; its inference reaches Bonsai on Raven
|
|
||||||
through a loopback tunnel, and sign-in goes through Heimdall, discovered via
|
|
||||||
Odin.
|
|
||||||
|
|
||||||
## How it deploys
|
What is in the tree is the kernel (`crates/ghostlight`), the persona projection
|
||||||
|
(`crates/ghostlight-persona-projection`), the verse runner
|
||||||
|
(`crates/ghostlight-verse`), and the Dungeon daemon (`crates/ghostlight-dungeon`).
|
||||||
|
`cargo test` runs them on Linux; use the `ygg-verify` stopgap on Yggdrasil, not
|
||||||
|
the workstation, and say which host you used.
|
||||||
|
|
||||||
Idunn is the only deploy path (`idunn up ghostlight`). The recipe is
|
Dungeon deployment and lifecycle on Yggdrasil are managed through Idunn from
|
||||||
`deployment/idunn/recipe.toml`; the runbook is
|
`deployment/idunn/recipe.toml` (runbook: `gamecult-ops/runbooks/ghostlight-dungeon-yggdrasil.md`).
|
||||||
`gamecult-ops/runbooks/ghostlight-dungeon-yggdrasil.md`. The Ghostlight daemon
|
Do not run the legacy v1 actuator or `ghostlight-dungeon.service`.
|
||||||
cannot start without Odin: its Warming presence and process write lease go
|
|
||||||
through Odin. Preflight Odin's route health before a deploy. Do not invoke the
|
|
||||||
retired v1 actuator (`gamecult-ops/scripts/deploy-ghostlight-yggdrasil.sh`), its
|
|
||||||
wiring test, or `ghostlight-dungeon.service`.
|
|
||||||
|
|
||||||
## Where open work is
|
## Where open work is
|
||||||
|
|
||||||
|
|
@ -35,13 +32,15 @@ target and probed body facts are `notes/ghostlight-verse-target.md` and
|
||||||
|
|
||||||
1. `README.md`: what exists and what does not.
|
1. `README.md`: what exists and what does not.
|
||||||
2. `AGENTS.md`: invariants and where things are.
|
2. `AGENTS.md`: invariants and where things are.
|
||||||
3. `docs/architecture/ghostlight-dungeon-mvp.md`: the authority architecture.
|
3. `docs/architecture/ghostlight-world-ontology.md`: the kernel's vocabulary and
|
||||||
4. `docs/architecture/ghostlight-world-ontology.md`: the kernel's vocabulary and
|
|
||||||
current mechanism.
|
current mechanism.
|
||||||
|
4. `docs/architecture/ghostlight-dungeon-mvp.md`: the earlier Dungeon / parked Eve
|
||||||
|
surface authority architecture (historical design record; `crates/ghostlight-dungeon`
|
||||||
|
is the live playtest daemon).
|
||||||
5. `docs/architecture/ghostlight-play-agent-cut.md`: the dated record of the play
|
5. `docs/architecture/ghostlight-play-agent-cut.md`: the dated record of the play
|
||||||
agent and of the first deploy on 2026-09-23 (findings PA.f198 to PA.f216).
|
agent and of the first deploy on 2026-09-23 (findings PA.f198 to PA.f216).
|
||||||
It is history; the mind says which findings are still open.
|
It is history; the mind says which findings are still open.
|
||||||
|
|
||||||
`notes/local-live-smoke.md` covers bringing up the Claude SDK sidecar by hand.
|
`notes/local-live-smoke.md` covers local loopback/hosted smoke runs.
|
||||||
`notes/ghostlight-implementation-plan.md` is the historical plan of the 2026-09
|
`notes/ghostlight-implementation-plan.md` is the historical plan of the 2026-09
|
||||||
rebuild.
|
rebuild.
|
||||||
|
|
|
||||||
|
|
@ -496,144 +496,9 @@ region-wide or global witness still discards a grouped cell's in-flight work
|
||||||
for every constituent it touches, which is the debt this pass explicitly
|
for every constituent it touches, which is the debt this pass explicitly
|
||||||
declined to pay.
|
declined to pay.
|
||||||
|
|
||||||
### 11. Claude SDK inference port — landed
|
### 11. Inference routing and road follow-ups (historical)
|
||||||
|
|
||||||
Objective: run Ghostlight's inference lanes on the Claude subscription while
|
(Historical transport section removed; `RoutedInferencePort` routes prefix-claimed `local/` and `hosted/` lanes and falls through to the connector.)
|
||||||
no Codex subscription or API budget exists, without moving the harness.
|
|
||||||
|
|
||||||
Landed mechanism: two `InferencePort` implementors behind one
|
|
||||||
`RoutedInferencePort`, chosen per lane by the configured model's prefix
|
|
||||||
(`GHOSTLIGHT_SDK_MODEL_PREFIX`, default `claude`) — a `claude`-prefixed model
|
|
||||||
reaches `SdkInferencePort`, anything else reaches the existing
|
|
||||||
`CodexConnectorInferencePort` unchanged. `SdkInferencePort` spawns a Node
|
|
||||||
sidecar (`sidecar/claude-sdk/`, a TypeScript package on
|
|
||||||
`@anthropic-ai/claude-agent-sdk` `0.3.261`, `@msgpack/msgpack` `3.1.3`, and
|
|
||||||
`zod` `4.5.4`, all exact-pinned) as a child process over stdio, framed as a
|
|
||||||
4-byte big-endian length prefix plus `rmp_serde::to_vec_named` bytes. One
|
|
||||||
request is one SDK query with the system prompt replaced, built-ins
|
|
||||||
stripped, settings sources empty, the request's tools registered as
|
|
||||||
in-process SDK tools, a derived turn cap, and the request's model.
|
|
||||||
Execute-through: each tool call the model makes crosses the pipe and is
|
|
||||||
answered by `ToolResultOracle`, one trait with four implementors
|
|
||||||
(`InterpreterOracle`, `OperationalOracle`, `GroupedOracle`,
|
|
||||||
`ElaborationOracle`) — each is the lane's own evaluator fold, extracted
|
|
||||||
whole into a free function (`interpreter_tool_result`,
|
|
||||||
`operational_tool_result`, `grouped_tool_result`, and the already-factored
|
|
||||||
`apply_tool_call`) and replayed over `completed` at construction, so the
|
|
||||||
string handed to the model is the same one re-derivation will recompute.
|
|
||||||
The sidecar computes no tool result itself.
|
|
||||||
|
|
||||||
One free function, `prepare_invocation`, is the sole owner of prepared
|
|
||||||
identity for both ports; `ControllerRunner::open` is injection-only —
|
|
||||||
`with_test_ports` is gone, and `open` takes `Arc<dyn InferencePort>`,
|
|
||||||
`Arc<dyn ControllerWorkStore>`, and `ControllerModels` and nothing
|
|
||||||
transport-specific. `runtime::open_controller` builds `ConnectorBinding`
|
|
||||||
and `SdkBinding` from the environment and calls `open_inference`, then
|
|
||||||
`open_controller_work`, then `ControllerRunner::open`; `open_inference`
|
|
||||||
routes every one of the five `ControllerModels` at open time and refuses a
|
|
||||||
model no configured backend claims (`ControllerOpenError::UnroutableModel`)
|
|
||||||
or a sidecar entry that is not a file
|
|
||||||
(`ControllerOpenError::SdkSidecarMissing`) before the first tick, not after.
|
|
||||||
|
|
||||||
Environment: `GHOSTLIGHT_SDK_SIDECAR` (the built sidecar entry path; its
|
|
||||||
absence means no SDK binding, not a default path) and
|
|
||||||
`GHOSTLIGHT_SDK_MODEL_PREFIX` (default `claude`) are read once in
|
|
||||||
`runtime::open_controller`. `GHOSTLIGHT_CONTROLLER_CREDENTIAL` is no longer
|
|
||||||
unconditionally required — an SDK-only configuration reads no credential
|
|
||||||
path at all. `GHOSTLIGHT_WRITE_SIDECAR_FIXTURES` regenerates the checked-in
|
|
||||||
schema and frame fixtures the Rust and TypeScript sides pin against each
|
|
||||||
other; it is a fixture-authoring switch, not a runtime binding.
|
|
||||||
|
|
||||||
Cut line held: no second identity scheme (`prepare_invocation` is the one
|
|
||||||
owner, both ports call it); no daemon, network port, or CultMesh surface for
|
|
||||||
the sidecar (it is a plain child process, restarted on fault, holding no
|
|
||||||
query state between queries); no credential handling in Ghostlight (the
|
|
||||||
sidecar inherits the ambient Claude Code login and this repo reads, copies,
|
|
||||||
forwards, or logs none of it); the connector port and its `execute` are
|
|
||||||
untouched; the port is chosen per lane by the configured model, with no mode
|
|
||||||
flag. Two forks the original design did not anticipate: `ControllerRunner::open`
|
|
||||||
became injection-only rather than keeping a `#[cfg(test)]` twin, because
|
|
||||||
removing the two transport-specific parameters made the twin's only purpose
|
|
||||||
vanish; and the turn cap rides on the oracle (`remaining_rounds`) rather than
|
|
||||||
on `InferencePurpose`, because the elaboration and seed lanes share one
|
|
||||||
purpose but carry different round budgets.
|
|
||||||
|
|
||||||
Named liabilities, stated where `SdkInferencePort` is defined, not hidden in
|
|
||||||
the lowering:
|
|
||||||
|
|
||||||
- The receipt is the SDK's message, not wire bytes. Its identity half is
|
|
||||||
computed from the invocation Ghostlight already holds; its provenance half
|
|
||||||
is a session id and message uuids reported by a child process this port
|
|
||||||
spawned. It attests that this exact request produced this exact SDK
|
|
||||||
session; it does not attest against a party Ghostlight does not control,
|
|
||||||
which is what the connector's receipt does.
|
|
||||||
- A prior round's conversation reaches the model as prose, not as typed
|
|
||||||
turns. The SDK owns the assistant side of its own transcript, so typed
|
|
||||||
`tool_call`/`tool_result` turns from an earlier round cannot be replayed
|
|
||||||
into it; they are rendered as strings under one fixed header and appended
|
|
||||||
to the prompt.
|
|
||||||
- The Zod validation of a tool call's arguments happens in the sidecar
|
|
||||||
before the handler runs, so a model's undecodable arguments never reach
|
|
||||||
Rust as an argument string the oracle can fold over; the sidecar reports
|
|
||||||
a normal dispatched tool call and Rust's own evaluator recomputes the
|
|
||||||
decode failure as an ordinary gap — on the connector path the same
|
|
||||||
failure is a gap recorded by the evaluator directly. Both are gaps; the
|
|
||||||
divergence in exactly which layer detects an undecodable argument can
|
|
||||||
only reach a later round's prompt through the prose transcript.
|
|
||||||
- `error_max_turns` handling is inferred from the SDK's own documentation,
|
|
||||||
not observed: the sidecar is written to catch the throw the TypeScript
|
|
||||||
SDK performs after yielding the error result, assemble the events already
|
|
||||||
collected, and emit a normal `Output` whose receipt records
|
|
||||||
`subtype: "error_max_turns"`, so the lane sees one ordinary round and
|
|
||||||
proceeds rather than faulting. No live query has exercised this path.
|
|
||||||
- Because the turn cap is the lane's *remaining* round budget and the lane
|
|
||||||
still counts rounds even when the cap is not reached, a lane whose model
|
|
||||||
never terminates in one turn can spend a triangular number of turns across
|
|
||||||
a round sequence (seed: 24+23+…, bounded by `SEED_ROUND_BUDGET`) against
|
|
||||||
the connector's flat per-round cost. This is unmeasured: no live run has
|
|
||||||
produced a number to weigh it against.
|
|
||||||
|
|
||||||
The SDK port has since carried the road runs recorded in the handoff (runs 8
|
|
||||||
to 12, through the sidecar, the only live provider). The ad-hoc smoke that
|
|
||||||
drove them was deleted with the tick driver in the play agent's Cut 1
|
|
||||||
(`d69e9d4`). No live smoke exists until the play agent's gate.
|
|
||||||
|
|
||||||
Exit condition, unchanged from the port's own doc comment: when an
|
|
||||||
`ANTHROPIC_API_KEY` and a budget exist, a Messages-API port is a closer
|
|
||||||
structural match to `InferencePort` than the SDK is — inert `tool_use`
|
|
||||||
blocks, a caller-appended `tool_result`, a real request id, real
|
|
||||||
concurrency, no subprocess — and `SdkInferencePort` is deleted rather than
|
|
||||||
extended, keeping `RoutedInferencePort` and swapping what it routes to.
|
|
||||||
Rejected: a backend inside CodexConnector (a deliberately isolated Codex
|
|
||||||
fork).
|
|
||||||
|
|
||||||
One validator on both transports: the sidecar's schema conversion is loose
|
|
||||||
(every property optional, unknown keys kept), so the arguments the model
|
|
||||||
emitted reach Rust's decoder unstripped and a refused argument is the gap
|
|
||||||
the evaluator already records, on the SDK path exactly as on the connector
|
|
||||||
path. Residual: a property whose value has the wrong type reaches Rust as
|
|
||||||
absent rather than as the wrong value, because the SDK derives the
|
|
||||||
advertised tool schema from the same object and refuses a dynamic
|
|
||||||
pass-through; the decoder reports it as missing. The result-subtype mapping
|
|
||||||
(`error_max_turns` is an output; every error subtype a named fault) is
|
|
||||||
tested in the sidecar without a credential.
|
|
||||||
|
|
||||||
Road follow-ups, 2026-09-10, from the first two SDK-backed seeded runs
|
|
||||||
(`notes/local-live-smoke.md`, "Claude SDK route"): the sidecar's schema
|
|
||||||
conversion now carries every field `description` through to the advertised
|
|
||||||
tool schema (it dropped all of them, so the `claude` lane saw bare types);
|
|
||||||
`due` describes itself as a clock reading and both authoring prompts print
|
|
||||||
the clock, because the model wrote twelve commitments due at or before a
|
|
||||||
clock it was never shown; `declare_subject` states the grant rule at the
|
|
||||||
point of use; `apply_tool_call` logs each raw tool call at debug so a refused
|
|
||||||
patch is diagnosed from what the model sent. A kernel refusal now continues
|
|
||||||
the same conversation instead of opening a fresh draft: `Refusal { after_round,
|
|
||||||
mismatches }` rows on both authoring checkpoints (`controller_work.v12`;
|
|
||||||
prior rows refused, not migrated), the refusal rendered as the next user turn
|
|
||||||
after the rounds that earned it, and the draft rebuilt by one `DraftFold`
|
|
||||||
shared by the evaluator and the oracle from the calls after it. The harness
|
|
||||||
takes the connector binding only when `GHOSTLIGHT_CONTROLLER_CONNECTOR` is
|
|
||||||
set, so an all-`claude` run needs no connector.
|
|
||||||
|
|
||||||
From run 2: the Interpreter's `speak` and `record_gap` cite the source by
|
From run 2: the Interpreter's `speak` and `record_gap` cite the source by
|
||||||
quoting it (`source_quote`), and the harness locates the quote and derives
|
quoting it (`source_quote`), and the harness locates the quote and derives
|
||||||
|
|
@ -845,9 +710,8 @@ operation count sentence (line 459 still says twenty-nine; it is thirty and
|
||||||
stays thirty), and Interpreter paragraph follow.
|
stays thirty), and Interpreter paragraph follow.
|
||||||
|
|
||||||
Build budget: crate `ghostlight-dungeon` and `ghostlight-persona-projection`
|
Build budget: crate `ghostlight-dungeon` and `ghostlight-persona-projection`
|
||||||
tests on the Windows workstation as the proving host, sidecar schema
|
tests on the Windows workstation as the proving host; the Linux release is
|
||||||
fixtures regenerated if the Interpreter tool set changes the sidecar's
|
Idunn's build and is not touched by this cut.
|
||||||
fixture; the Linux release is Idunn's build and is not touched by this cut.
|
|
||||||
|
|
||||||
Verification: kernel tests that a display lands `Seen { by }` on the
|
Verification: kernel tests that a display lands `Seen { by }` on the
|
||||||
co-located only, never on the actor, never on a subject elsewhere or on a
|
co-located only, never on the actor, never on a subject elsewhere or on a
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,8 @@
|
||||||
# Ghostlight Verse: Map
|
# Ghostlight Verse: Map
|
||||||
|
|
||||||
Campaign `ghostlight-verse`, target `ghostlight-verse:target:r2`
|
> Status: Dungeon, eve.rs and the bridge-test references below are parked at tag `parked/ghostlight-eve-surface`; line refs are to that tag.
|
||||||
|
|
||||||
|
Campaign `ghostlight-verse`, target `ghostlight-verse:target:r3`
|
||||||
(`notes/ghostlight-verse-target.md`). This page holds body facts, the model
|
(`notes/ghostlight-verse-target.md`). This page holds body facts, the model
|
||||||
page and rationale only. Cut specs, questions, rulings and follow-ups live in
|
page and rationale only. Cut specs, questions, rulings and follow-ups live in
|
||||||
the Eureka mind; query them there, never copy them here.
|
the Eureka mind; query them there, never copy them here.
|
||||||
|
|
@ -9,6 +11,15 @@ Phase 1 map: Imagination, session `self-2026-10-09-morning`, 2026-10-09.
|
||||||
Base for every phase-1 anchor: Ghostlight `origin/main` `4fee97f`.
|
Base for every phase-1 anchor: Ghostlight `origin/main` `4fee97f`.
|
||||||
Times are UTC unless marked local (UTC+2).
|
Times are UTC unless marked local (UTC+2).
|
||||||
|
|
||||||
|
## Cut sequence
|
||||||
|
|
||||||
|
Cuts without a `cut_spec`, withdrawn 2026-10-12 under map-only-what-runs: a spec is admitted when Self is about to dispatch the cut. The live run waits on the operator's DeepSeek key. Re-map a line by a fresh Imagination pass against the Body when the frontier reaches it.
|
||||||
|
|
||||||
|
- model-asleep: The play card says the storyteller is waking while Bonsai reloads, and refuses a turn with an asleep line when the. Waits on: play-faults (live run waits on the operator DeepSeek key).
|
||||||
|
- raven-bonsai-scripts: Raven's Bonsai scripts enter gamecult-ops; the server stays up and sleeps its model on idle, the reaper is gone, and. Waits on: nothing in the mind (not queued; Ghostlight live run waits on the operator DeepSeek key).
|
||||||
|
- deploy-main: Main deploys on Yggdrasil through Idunn, stays up, and a human plays a session end to end. Waits on: play-faults, play-surface, session-refresh, acceptance-gate, raven-bonsai-scripts, model-asleep, create-flow (blocked on the DeepSeek key and the Ghostlight live-run chain).
|
||||||
|
- v1-retire: The retired v1 Ghostlight body leaves Yggdrasil and gamecult-ops. Waits on: nothing in the mind (not queued; Ghostlight frontier is the live run).
|
||||||
|
|
||||||
## Body facts (probed 2026-10-09)
|
## Body facts (probed 2026-10-09)
|
||||||
|
|
||||||
### Does main run on Yggdrasil?
|
### Does main run on Yggdrasil?
|
||||||
|
|
@ -57,7 +68,7 @@ Times are UTC unless marked local (UTC+2).
|
||||||
|
|
||||||
### Does main build and pass?
|
### Does main build and pass?
|
||||||
|
|
||||||
Two jobs through `ygg-verify.sh` at `4fee97f`, with `vendor/eve` initialised:
|
Two jobs through `ygg-verify.sh` at `4fee97f`, with the Eve submodule initialised:
|
||||||
|
|
||||||
- Rust (image `eureka-verify-rust`), the recipe's own steps:
|
- Rust (image `eureka-verify-rust`), the recipe's own steps:
|
||||||
`ghostlight-persona-projection` 35 passed; `ghostlight` lib 621 passed,
|
`ghostlight-persona-projection` 35 passed; `ghostlight` lib 621 passed,
|
||||||
|
|
@ -148,7 +159,15 @@ from 21:04 the denial forever. Mechanism:
|
||||||
that key can ever succeed, and `sessions_due_for_refresh`
|
that key can ever succeed, and `sessions_due_for_refresh`
|
||||||
(`app_session.rs:247-268`) keeps offering the same candidate while
|
(`app_session.rs:247-268`) keeps offering the same candidate while
|
||||||
`refresh_expires_at > now`. Which clause of `app_session.rs:293-299` fired at
|
`refresh_expires_at > now`. Which clause of `app_session.rs:293-299` fired at
|
||||||
21:03 is not logged.
|
21:03 is not logged, but only one is reachable: the session-id and account
|
||||||
|
clauses are pre-checked and revoked at `runtime.rs:1904-1916`, a revoked
|
||||||
|
session is never offered, and nothing else moves `access_revision`. That
|
||||||
|
leaves `input.access_revision() <= expected` (`app_session.rs:295`). Heimdall's
|
||||||
|
refresh reissues the claim with the refresh claim's `access_revision`
|
||||||
|
unchanged (`Heimdall/src/app.ts:716-724`; only logout bumps it,
|
||||||
|
`private-command-plane.ts:197`), so every real refresh is executed upstream
|
||||||
|
and refused locally, and the key `refresh:{sid}:{rev}` never changes within a
|
||||||
|
session. Question `ghostlight-verse:question:refresh-revision-contract`.
|
||||||
|
|
||||||
### The host
|
### The host
|
||||||
|
|
||||||
|
|
@ -194,6 +213,67 @@ from 21:04 the denial forever. Mechanism:
|
||||||
code is flat under `crates/ghostlight/src/`. Dated cut documents and
|
code is flat under `crates/ghostlight/src/`. Dated cut documents and
|
||||||
postmortems keep their paths: they are history.
|
postmortems keep their paths: they are history.
|
||||||
|
|
||||||
|
### Who refuses an operational in-flight row whose scope moved? (probed 2026-10-17, `4741d50`)
|
||||||
|
|
||||||
|
- Three paths answer the same fact (the subject still holds one opportunity on
|
||||||
|
the bound scope, at a new digest), with two errors. A probe test run on
|
||||||
|
Yggdrasil returned these, with one provider call in total:
|
||||||
|
- The scope moves during round 0 of a fresh run. Round 1's
|
||||||
|
`ensure_scope_unchanged` returns `NoOpportunity`.
|
||||||
|
- A resume passing the row's own stale opportunity returns `NoOpportunity`
|
||||||
|
(same gate).
|
||||||
|
- A resume passing the fresh opportunity returns `OpportunityMismatch`, from
|
||||||
|
the digest clause of `row_answers_caller` at lookup.
|
||||||
|
- The driver's `classify` (`verse/run.rs` 641-651) labels the first two
|
||||||
|
`OpportunityGone` and the third `ScopeMoved`. That makes the first two
|
||||||
|
mislabels: the label's doc says `OpportunityGone` means the subject holds no
|
||||||
|
opportunity. Cause: when `select_scope`'s digest clause empties the match
|
||||||
|
list, it answers `NoOpportunity` (`controllers.rs` ~1552).
|
||||||
|
- In the narrative lane, the lookup digest clause is the only gate. A driver
|
||||||
|
resume with the fresh opportunity is refused there. Fork A's kernel-refusal
|
||||||
|
re-lowering (`1ef973a`) runs only when a caller passes the stale opportunity.
|
||||||
|
- Grouped lane (probed 2026-10-17, `771a79d`, by reading; `select_one` now
|
||||||
|
returns `ScopeMoved`): `run_group` maps every `select_one` error to
|
||||||
|
`LeftBeforeSelection`, which the driver records as `OpportunityGone`. A member
|
||||||
|
whose scope moved is dropped before any constituent, inference or submission
|
||||||
|
exists, so only the label is wrong; spend is identical and nothing branches on
|
||||||
|
the reason (`grouped-record-and-carry` keys on membership in `refused`). Own
|
||||||
|
cut: `cut-grouped-scope-moved-label.r1`.
|
||||||
|
|
||||||
|
### Who refuses a resumed narrative row whose scope moved? (probed 2026-10-17, `73f26a5`)
|
||||||
|
|
||||||
|
- **Today, at lookup, by the caller's digest.** `run_narrative`'s Confirmed
|
||||||
|
and CustodyUncertain arms (`controllers.rs` 3144, 3152) call
|
||||||
|
`row_answers_caller`, the only callers it has since `in-flight-gate`
|
||||||
|
(`771a79d`). A fresh caller is refused `OpportunityMismatch`; a stale caller
|
||||||
|
passes to Fork A. Nothing in Projector, Persona or Interpreter rounds reads
|
||||||
|
the world (source read: `self.select` is called only at fresh run, round
|
||||||
|
checks of the operational lane, and the other lanes' fresh paths).
|
||||||
|
- **The kernel path is already whole.** `submit_narrative`'s `ScopeChanged`
|
||||||
|
arm calls `interrupted`, which re-lowers once. A second move reads
|
||||||
|
`interrupted_from.is_some()` and ends the turn `overtaken`, with nothing
|
||||||
|
submitted and no further inference. The progression arm (~2375) refuses to
|
||||||
|
persist a second re-lowering even if the runner tried. Pinned by
|
||||||
|
`a_second_scope_change_after_the_re_lowering_spends_nothing`.
|
||||||
|
- **Probe** (Yggdrasil, ygg-verify rust, clone at `73f26a5`, sed in the job;
|
||||||
|
script `probe1.sh` in the imagination-ag5-narrative scratchpad): both lookup
|
||||||
|
arms put on `same_decision`, and `OpportunityMismatch` moved from `ScopeMoved`
|
||||||
|
to `OpportunityGone` in `classify`. `cargo test -p ghostlight --lib`: 803
|
||||||
|
passed, 3 failed. The failures were
|
||||||
|
`a_narrative_row_in_flight_whose_scope_moved_is_refused_before_inference`
|
||||||
|
(the resumed row now called the provider and ran the test port dry),
|
||||||
|
`a_narrative_row_in_flight_in_uncertain_custody_keeps_the_digest_gate`, and
|
||||||
|
`an_error_ends_a_cell_as_the_run_must_treat_it` (the classify table). No
|
||||||
|
verse driver test reached `ScopeMoved` through `OpportunityMismatch`.
|
||||||
|
- **`OpportunityMismatch` is no longer a moved scope anywhere.** After the cut
|
||||||
|
it arises from `same_decision` (another decision), `select_scope`'s
|
||||||
|
controller-id check, and the Persona lane's forged-field refusals. The driver
|
||||||
|
cannot reach a `same_decision` mismatch, because `run_cell` derives the
|
||||||
|
command id from world, cell, subject and tick.
|
||||||
|
- **Dead code.** Both `awaits_world` methods have no production caller once
|
||||||
|
`row_answers_caller` goes. The operational one has been test-only since
|
||||||
|
`771a79d`. The only other reader is the `NeverSentStore` test fixture.
|
||||||
|
|
||||||
## Model page
|
## Model page
|
||||||
|
|
||||||
One row per persistent kind phase 1 touches. No cell may be empty.
|
One row per persistent kind phase 1 touches. No cell may be empty.
|
||||||
|
|
@ -201,13 +281,14 @@ One row per persistent kind phase 1 touches. No cell may be empty.
|
||||||
| Kind | Named by | Life over time | Who decides |
|
| Kind | Named by | Life over time | Who decides |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| World state and commit journal (`.cc`, redb) | `WorldId`; `revision`; digest chain | created Draft, approved, activated; one commit row per admitted command; earlier schemas refused, never migrated | the kernel, through `WorldMailbox`'s closed operation set; untouched in phase 1 |
|
| World state and commit journal (`.cc`, redb) | `WorldId`; `revision`; digest chain | created Draft, approved, activated; one commit row per admitted command; earlier schemas refused, never migrated | the kernel, through `WorldMailbox`'s closed operation set; untouched in phase 1 |
|
||||||
| Play turn row (play-turn store `.cc`) | `turn_id` (UUID); per-turn `question_token` | `Running` → `AwaitingPlayer` ↔ `Running` → `Closed` (narration or `fault`); an unreadable row is retired to a sidecar and play starts fresh | `PlayTable` (`play.rs`); the card is a projection of `PlayTurnView`, which phase 1 extends with the fault |
|
| Play turn row (play-turn store `.cc`) | `turn_id` (UUID); per-turn `question_token` | `Running` → `AwaitingPlayer` ↔ `Running` → `Closed` (narration or `fault`); earlier schemas and unreadable rows are refused on open, never migrated or retired to a sidecar | `PlayTable` (`play.rs`); the card is a projection of `PlayTurnView`, which phase 1 extends with the fault |
|
||||||
| App session (`app-sessions-v2.cc`) | cookie hash; `heimdall_session_id` + `access_revision` | issued at sign-in; refreshed when access is near expiry; revoked on logout, custody change, invalid receipt, and (phase 1) on a refresh that can no longer succeed | `AppSessionOwner`; Heimdall decides the upstream session and rotates refresh tokens |
|
| App session (`app-sessions-v2.cc`) | cookie hash; `heimdall_session_id` + `access_revision` | issued at sign-in; refreshed when access is near expiry; revoked on logout, custody change, invalid receipt, and (phase 1) on a refresh that can no longer succeed | `AppSessionOwner`; Heimdall decides the upstream session and rotates refresh tokens |
|
||||||
| Heimdall private command receipt (Heimdall Postgres) | `(app_slug, idempotency_key)` + request fingerprint | written once per executed command; replayed for an identical request; a different request under the key is refused | Heimdall; its fingerprint rule is a Heimdall follow-up, not a phase-1 cut |
|
| Heimdall private command receipt (Heimdall Postgres) | `(app_slug, idempotency_key)` + request fingerprint | written once per executed command; replayed for an identical request; a different request under the key is refused | Heimdall; its fingerprint rule is a Heimdall follow-up, not a phase-1 cut |
|
||||||
| Idunn generation (transient unit, release dir) | `sha256-<release>` | staged → started → Warming → lease → Active → superseded or failed; the previous Active stays until a new one is Ready | Idunn; retention and failed-unit collection are Idunn's follow-up |
|
| Idunn generation (transient unit, release dir) | `sha256-<release>` | staged → started → Warming → lease → Active → superseded or failed; the previous Active stays until a new one is Ready | Idunn; retention and failed-unit collection are Idunn's follow-up |
|
||||||
| v1 body (`ghostlight-dungeon.service`, `/srv/ghostlight`, v1 state) | unit name; paths | retired in fact 2026-09-23; unit still enabled | nobody today; phase 1 assigns its removal to a gamecult-ops cut, data by operator ruling |
|
| v1 body (`ghostlight-dungeon.service`, `/srv/ghostlight`, v1 state) | unit name; paths | retired in fact 2026-09-23; unit still enabled | nobody today; phase 1 assigns its removal to a gamecult-ops cut, data by operator ruling |
|
||||||
| Bonsai lifecycle (Raven containers) | container `bonsai`; scripts under `/opt/gamecult/bonsai` | started by hand ("Start AI Chat"); restarted by the RSS watchdog; stopped by the idle reaper | gamecult-ops/Raven; Dungeon only reads the endpoint; availability policy is an operator question |
|
| Bonsai lifecycle (Raven containers) | container `bonsai`; scripts under `/opt/gamecult/bonsai` | started by hand ("Start AI Chat"); restarted by the RSS watchdog; stopped by the idle reaper | gamecult-ops/Raven; Dungeon only reads the endpoint; availability policy is an operator question |
|
||||||
| Repository docs (README, AGENTS, live architecture pages, handoff) | path on `main` | rewritten to the live machine; pre-rebuild material leaves `main` by operator ruling | the Ghostlight repo; history in git, dated cut documents and postmortems |
|
| Repository docs (README, AGENTS, live architecture pages, handoff) | path on `main` | rewritten to the live machine; pre-rebuild material leaves `main` by operator ruling | the Ghostlight repo; history in git, dated cut documents and postmortems |
|
||||||
|
| Controller-work row (`controller-work.cc`, narrative and operational checkpoints) | `CommandId` (driver: derived from world, cell, subject, tick) | persisted before each spend; advanced only by the progression rule; a narrative row re-lowers at most once (`interrupted_from`), then commits, declines or ends overtaken | which decision a row answers: `same_decision`, both lanes, the caller naming identity only. Whether its scope moved: the world (operational: `ensure_scope_unchanged` before each round; narrative: the kernel's `ScopeChanged` at submit, answered by `interrupted`). Labels: `classify` alone |
|
||||||
|
|
||||||
### Where phase 2's verb sets plug in
|
### Where phase 2's verb sets plug in
|
||||||
|
|
||||||
|
|
@ -256,3 +337,16 @@ verbs as the target.
|
||||||
Dungeon tests that drive the real client, and nothing runs them. Fixing the
|
Dungeon tests that drive the real client, and nothing runs them. Fixing the
|
||||||
gate means a runner with both Rust and Node, which is Idunn's recipe and
|
gate means a runner with both Rust and Node, which is Idunn's recipe and
|
||||||
runner surface: a follow-up, with each phase-1 Hands run doing them by hand.
|
runner surface: a follow-up, with each phase-1 Hands run doing them by hand.
|
||||||
|
- **A narrative resume has one detector, and it is the kernel** (ruling
|
||||||
|
`narrative-resume-relowers`). The caller's opportunity names the decision
|
||||||
|
and nothing more, in both lanes, through the one `same_decision`. The lanes
|
||||||
|
differ only in when the world is asked. The operational lane asks before each
|
||||||
|
round, because it has nothing to preserve. The narrative lane asks at submit,
|
||||||
|
because its prose and receipts survive to be lowered again. The price is the
|
||||||
|
remaining rounds plus at most one Interpreter call. `OpportunityMismatch`
|
||||||
|
then stops meaning a moved scope, so `classify` labels it `OpportunityGone`,
|
||||||
|
as the grouped lane already does. Keeping it on `ScopeMoved` would leave a
|
||||||
|
second, wrong answer to "did the scope move". The grouped selection label
|
||||||
|
becomes a pure function, because `AmbiguousOpportunity` cannot be built
|
||||||
|
through a live world, which offers one opportunity per scope. Pinning the
|
||||||
|
function is what closes follow-up `grouped-left-arms-pin`.
|
||||||
|
|
|
||||||
|
|
@ -1,95 +1,39 @@
|
||||||
# Connector And Claude SDK Sidecar Bring-Up
|
# Connector Bring-Up
|
||||||
|
|
||||||
No live smoke exists in this tree. The ignored test this file once documented,
|
No automated live smoke exists in this tree. The one real-model test left is the
|
||||||
`runtime::tests::live_smoke_seeds_then_ticks_a_world_against_the_connector`,
|
ignored `controllers::tests::real_local_model_cognition_modes_commit_speech`
|
||||||
ran the production tick driver and the Active elaboration sweep against a real
|
(`crates/ghostlight/src/controllers.rs`), and a person runs it by hand with
|
||||||
CodexConnector; the play agent's Cut 1 (`d69e9d4`) deleted both, and the test
|
`cargo test -p ghostlight -- --ignored real_local_model_cognition_modes_commit_speech`.
|
||||||
with them. A command that names it now matches nothing and exits 0. No
|
It needs either a local model server (`GHOSTLIGHT_LOCAL_ENDPOINT`) or the
|
||||||
replacement exists. The real-model gate that does exist is the Idunn recipe's
|
connector (`GHOSTLIGHT_ACCEPTANCE_CONNECTOR=<host:port>` plus the systemd
|
||||||
`accept-real-persona-membrane` step (`deployment/idunn/recipe.toml`).
|
credential below), and the `GHOSTLIGHT_CONTROLLER_*_MODEL`,
|
||||||
|
`GHOSTLIGHT_ACCEPTANCE_RUNTIME_ID` and `GHOSTLIGHT_ACCEPTANCE_PERSONA_PROSE_LOG`
|
||||||
|
variables. The release gate passes if one of three attempts commits; every
|
||||||
|
failed attempt's prose is kept.
|
||||||
|
|
||||||
What remains true and stays here: bringing up a real CodexConnector and a
|
## The connector
|
||||||
built Claude SDK sidecar. The seed lane (`world.seed`) still runs real
|
|
||||||
inference through `ControllerRunner`, and both transports below are how a
|
|
||||||
session gets real model responses instead of a fixture inference port.
|
|
||||||
|
|
||||||
## Substrate
|
Ghostlight's connector lane speaks model-connector v4 to claude-connector, which
|
||||||
|
Eureka owns and runs on Yggdrasil at `127.0.0.1:4110`. Ghostlight is one of its
|
||||||
|
callers, identified as `ghostlight`. Connector models are `claude-haiku-5-5`,
|
||||||
|
`claude-sonnet-5-5` and `claude-opus-5-5`; any other name is refused
|
||||||
|
`ModelNotAllowed`. A required tool choice on `claude-sonnet-5-5` is refused as
|
||||||
|
an invalid request, and Ghostlight sends only `Auto`.
|
||||||
|
|
||||||
Machine-local, outside the repo: `F:\Projects\Ghostlight-smoke\`.
|
The connection key is never copied, printed or put in an environment variable.
|
||||||
|
`ConnectorBinding::key_path` names a file, read once when the port opens. Under
|
||||||
- `codex-home\auth.json`: a copy of `~/.codex/auth.json`. The connector spawns
|
systemd that file is the credential the unit mounts:
|
||||||
the official `codex app-server` child against this home and may refresh it.
|
|
||||||
- `connector\ghostlight.key`: 64 hex characters, no trailing newline; the
|
|
||||||
shared connection secret. Both sides read the same file.
|
|
||||||
- `connector\connector.cc`: the daemon's single-caller config.
|
|
||||||
- `logs\`: connector stdout/stderr and pid.
|
|
||||||
|
|
||||||
The connector binary is `F:\Projects\CodexConnector\target\debug\codex-connector.exe`
|
|
||||||
built from the repo head with the `daemon` feature. Ghostlight's `Cargo.lock`
|
|
||||||
pins the connector library at an older revision whose daemon does not build
|
|
||||||
against its own lockfile; the head daemon speaks the same wire law.
|
|
||||||
|
|
||||||
## Bring-up
|
|
||||||
|
|
||||||
Initialize the config once (the codex executable path and SHA-256 are the
|
|
||||||
newest `codex.exe` under `%LOCALAPPDATA%\OpenAI\Codex\bin\`):
|
|
||||||
|
|
||||||
```powershell
|
|
||||||
F:\Projects\CodexConnector\target\debug\codex-connector.exe --initialize-single-caller-config F:\Projects\Ghostlight-smoke\connector\connector.cc 127.0.0.1:4103 <codex.exe> <sha256> F:\Projects\Ghostlight-smoke\codex-home F:\Projects\Ghostlight-smoke\connector\replay.cc ghostlight-smoke F:\Projects\Ghostlight-smoke\connector\ghostlight.key 1 gpt-5.6-luna,gpt-5.6-sol,gpt-5.6-terra 4 1052672 16000
|
|
||||||
```
|
|
||||||
|
|
||||||
Start the daemon detached; it prints one ready line to stderr:
|
|
||||||
|
|
||||||
```powershell
|
|
||||||
$R='F:\Projects\Ghostlight-smoke'; $p = Start-Process -FilePath 'F:\Projects\CodexConnector\target\debug\codex-connector.exe' -ArgumentList @('--config', "$R\connector\connector.cc") -RedirectStandardOutput "$R\logs\connector.stdout.log" -RedirectStandardError "$R\logs\connector.stderr.log" -PassThru -WindowStyle Hidden; $p.Id | Out-File "$R\logs\connector.pid"
|
|
||||||
```
|
|
||||||
|
|
||||||
Stop it with `Stop-Process -Id (Get-Content F:\Projects\Ghostlight-smoke\logs\connector.pid)`.
|
|
||||||
|
|
||||||
A session that wants the connector reads
|
|
||||||
`GHOSTLIGHT_CONTROLLER_CONNECTOR=127.0.0.1:4103` and
|
|
||||||
`GHOSTLIGHT_CONTROLLER_CREDENTIAL='F:\Projects\Ghostlight-smoke\connector\ghostlight.key'`,
|
|
||||||
the same variables the deleted harness read.
|
|
||||||
|
|
||||||
## Claude SDK route
|
|
||||||
|
|
||||||
`crates/ghostlight/src/sdk_inference.rs`'s `SdkInferencePort` gives any lane whose configured
|
|
||||||
model is `claude`-prefixed (matching `GHOSTLIGHT_SDK_MODEL_PREFIX`, default
|
|
||||||
`claude`) a second transport: a Node sidecar on the Claude Agent SDK instead of
|
|
||||||
the CodexConnector, so a session can run on the Claude subscription with no
|
|
||||||
Codex budget.
|
|
||||||
|
|
||||||
**Operator prerequisites, none of which Ghostlight performs:**
|
|
||||||
|
|
||||||
1. Install the Claude Code CLI.
|
|
||||||
2. Sign in with `/login`, or mint a token with `claude setup-token`.
|
|
||||||
3. Verify the login with one plain `claude -p` query.
|
|
||||||
|
|
||||||
The harness never reads, copies, forwards, or logs that credential; the
|
|
||||||
sidecar inherits it from the ambient environment the same way the CLI does.
|
|
||||||
|
|
||||||
**Build the sidecar**, once the CLI login is verified:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm --prefix sidecar/claude-sdk install
|
sudo systemd-run --wait --pipe \
|
||||||
npm run sdk:build
|
-p LoadCredential=connector-key:/etc/gamecult/claude-connector/connection-ghostlight.key \
|
||||||
|
-E GHOSTLIGHT_ACCEPTANCE_CONNECTOR=127.0.0.1:4110 ... <test binary> --ignored
|
||||||
```
|
```
|
||||||
|
|
||||||
`npm run sdk:build` is the root `package.json` alias for
|
The ignored `live_connector_v4_completes_plain_tool_and_schema_requests` runs the
|
||||||
`npm --prefix sidecar/claude-sdk run build`, emitting
|
same way (it needs only `CREDENTIALS_DIRECTORY`) and checks a plain, a tool and
|
||||||
`sidecar/claude-sdk/dist/main.js`.
|
an output-schema request on haiku and a plain request on sonnet.
|
||||||
|
|
||||||
**Environment**, in addition to the connector variables above:
|
Ghostlight's port is one shot
|
||||||
|
and returns a typed fault (`InferenceFaultClass`) whose disposition says whether
|
||||||
```bash
|
the owning flow may try again.
|
||||||
GHOSTLIGHT_SDK_SIDECAR='F:\Projects\Ghostlight\sidecar\claude-sdk\dist\main.js'
|
|
||||||
GHOSTLIGHT_SDK_MODEL_PREFIX=claude # optional; this is already the default
|
|
||||||
```
|
|
||||||
|
|
||||||
`GHOSTLIGHT_SDK_SIDECAR`'s absence means no SDK binding at all — a
|
|
||||||
`claude`-prefixed lane model then fails at open with `UnroutableModel` rather
|
|
||||||
than silently reaching the connector. Any of the five
|
|
||||||
`GHOSTLIGHT_CONTROLLER_*_MODEL` variables can be set to a `claude`-prefixed
|
|
||||||
model (for example `claude-opus-5`) to route that lane through the sidecar;
|
|
||||||
the connector variables are only required for lanes that still route to the
|
|
||||||
connector, and an all-`claude` configuration needs neither.
|
|
||||||
|
|
|
||||||
|
|
@ -2,14 +2,7 @@
|
||||||
"name": "ghostlight",
|
"name": "ghostlight",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "0.0.0",
|
"version": "0.0.0",
|
||||||
"description": "Ghostlight: the Rust kernel for socially situated agents, and Ghostlight Dungeon, the single-player DM-led client.",
|
"description": "Ghostlight: the Rust kernel for socially situated agents.",
|
||||||
"scripts": {
|
|
||||||
"dungeon:build": "cargo build --workspace && npm --prefix web run build",
|
|
||||||
"dungeon:test": "cargo test --workspace && npm --prefix web run build",
|
|
||||||
"dungeon:run": "cargo run -p ghostlight-dungeon",
|
|
||||||
"sdk:build": "npm --prefix sidecar/claude-sdk run build",
|
|
||||||
"sdk:test": "npm --prefix sidecar/claude-sdk test"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"inkjs": "^2.4.0"
|
"inkjs": "^2.4.0"
|
||||||
}
|
}
|
||||||
|
|
|
||||||
76
probes/page/begin-era.mjs
Normal file
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
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
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
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();
|
||||||
102
scripts/playtest-yggdrasil.sh
Normal file
102
scripts/playtest-yggdrasil.sh
Normal file
|
|
@ -0,0 +1,102 @@
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
# Run the Dungeon playtest on Yggdrasil: build the test binary once, then run it
|
||||||
|
# detached under a transient systemd unit that loads the Ghostlight connector key.
|
||||||
|
#
|
||||||
|
# scripts/playtest-yggdrasil.sh [--turns N] [--worlds id,id] [--wall-minutes M]
|
||||||
|
# [--out DIR] [--rev REV]
|
||||||
|
# scripts/playtest-yggdrasil.sh --atlas [--set NAME=VALUE ...] [--rev REV]
|
||||||
|
#
|
||||||
|
# --atlas runs the elaboration-only world atlas (playtest::atlas::live_atlas) instead of
|
||||||
|
# the play-through; each --set becomes an environment variable of the unit. The atlas knobs
|
||||||
|
# are GHOSTLIGHT_ATLAS_{VAULT,ERA,PERSONS,INSTITUTIONS,POPULATIONS,SWEEPS,SWEEP_SESSIONS,
|
||||||
|
# SEED_SESSIONS,TOKEN_CAP,CONCURRENCY}; set GHOSTLIGHT_CONTROLLER_MAX_CONCURRENT (the pool Begin
|
||||||
|
# seeds under) to the same concurrency, or the run refuses to start.
|
||||||
|
#
|
||||||
|
# Defaults: every world in crates/ghostlight-dungeon/playtest/plan.json, 12 turns
|
||||||
|
# per character, 240 minutes of wall time. Run it from a worktree with the
|
||||||
|
# Eureka skill's ygg-verify.sh reachable as $YGG_VERIFY (default
|
||||||
|
# ~/.claude/skills/eureka/tools/stopgap/ygg-verify.sh). The launcher clones REV on
|
||||||
|
# Yggdrasil, builds there, and exits once the unit is running; the unit keeps going.
|
||||||
|
# Vault copies live under $VAULT_BASE (default ~/ghostlight-playtest/vaults, holding
|
||||||
|
# AetheriaLore/Aetheria and Delvehold/Delvehold); output goes under $OUT_BASE.
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
IMAGE=${IMAGE:-eureka-verify-rust:b99d30ec441e}
|
||||||
|
KEY=${KEY:-/etc/gamecult/claude-connector/connection-ghostlight.key}
|
||||||
|
CONNECTOR_ADDR=${CONNECTOR_ADDR:-127.0.0.1:4110}
|
||||||
|
turns=""; worlds=""; wall=""; out=""; rev=""; on_host=0; stamp=""; atlas=0; sets=()
|
||||||
|
while [ $# -gt 0 ]; do
|
||||||
|
case "$1" in
|
||||||
|
--turns) turns=$2; shift 2 ;;
|
||||||
|
--worlds) worlds=$2; shift 2 ;;
|
||||||
|
--wall-minutes) wall=$2; shift 2 ;;
|
||||||
|
--out) out=$2; shift 2 ;;
|
||||||
|
--rev) rev=$2; shift 2 ;;
|
||||||
|
--on-host) on_host=1; shift ;;
|
||||||
|
--stamp) stamp=$2; shift 2 ;;
|
||||||
|
--atlas) atlas=1; shift ;;
|
||||||
|
--set) sets+=("$2"); shift 2 ;;
|
||||||
|
*) echo "unknown argument $1" >&2; exit 2 ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
if [ "$on_host" = 0 ]; then
|
||||||
|
here=$(cd "$(dirname "$0")/.." && pwd)
|
||||||
|
rev=${rev:-$(git -C "$here" rev-parse --short HEAD)}
|
||||||
|
stamp=$(date -u +%Y-%m-%dT%H%MZ)
|
||||||
|
verify=${YGG_VERIFY:-$HOME/.claude/skills/eureka/tools/stopgap/ygg-verify.sh}
|
||||||
|
args="--on-host --rev $rev --stamp $stamp"
|
||||||
|
[ -n "$turns" ] && args="$args --turns $turns"
|
||||||
|
[ -n "$worlds" ] && args="$args --worlds $worlds"
|
||||||
|
[ -n "$wall" ] && args="$args --wall-minutes $wall"
|
||||||
|
[ -n "$out" ] && args="$args --out $out"
|
||||||
|
[ "$atlas" = 1 ] && args="$args --atlas"
|
||||||
|
for kv in "${sets[@]}"; do args="$args --set $kv"; done
|
||||||
|
RUN_ON_HOST=1 TIMEOUT=3000 bash "$verify" "$here" "$rev" "$IMAGE" "bash scripts/playtest-yggdrasil.sh $args"
|
||||||
|
exit $?
|
||||||
|
fi
|
||||||
|
|
||||||
|
# On the Yggdrasil host, inside the clone of REV.
|
||||||
|
base=${PLAYTEST_BASE:-$HOME/ghostlight-playtest}
|
||||||
|
out=${out:-$base/out}
|
||||||
|
bin_dir=$base/bin
|
||||||
|
mkdir -p "$bin_dir" "$out"
|
||||||
|
bin=$bin_dir/ghostlight-dungeon-$rev
|
||||||
|
if [ ! -x "$bin" ]; then
|
||||||
|
sudo docker run --rm --cpus=4 --memory=6g \
|
||||||
|
-v "$PWD:/src" -v eureka-cargo-home:/cargo-home -e CARGO_HOME=/cargo-home \
|
||||||
|
-v /etc/machine-id:/etc/machine-id:ro -e GIT_CONFIG_COUNT=1 -e GIT_CONFIG_KEY_0=safe.directory -e GIT_CONFIG_VALUE_0='*' \
|
||||||
|
-e GHOSTLIGHT_BUILD_COMMIT="$rev" -v "$bin_dir:/out" -w /src "$IMAGE" bash -c '
|
||||||
|
set -euo pipefail
|
||||||
|
exe=$(cargo test --locked -p ghostlight-dungeon --no-run --message-format=json 2>/out/build.log \
|
||||||
|
| grep "\"test\":true" | grep "\"executable\":\"[^\"]*/ghostlight_dungeon-" \
|
||||||
|
| sed "s/.*\"executable\":\"\([^\"]*\)\".*/\1/" | tail -1)
|
||||||
|
test -n "$exe"
|
||||||
|
cp "$exe" /out/ghostlight-dungeon-'"$rev"'
|
||||||
|
'
|
||||||
|
fi
|
||||||
|
test -x "$bin"
|
||||||
|
|
||||||
|
if [ "$atlas" = 1 ]; then kind=atlas; test_name=playtest::atlas::live_atlas; else kind=playtest; test_name=playtest::live_playtest; fi
|
||||||
|
unit=ghostlight-$kind-$stamp
|
||||||
|
env_args=(--setenv=GHOSTLIGHT_CONNECTOR_ADDR="$CONNECTOR_ADDR"
|
||||||
|
--setenv=GHOSTLIGHT_CONNECTOR_KEY_FILE="/run/credentials/$unit.service/connector-key"
|
||||||
|
--setenv=GHOSTLIGHT_VAULT_BASE="${VAULT_BASE:-$base/vaults}"
|
||||||
|
--setenv=GHOSTLIGHT_PLAYTEST_OUT="$out" --setenv=GHOSTLIGHT_PLAYTEST_STAMP="$stamp" --setenv=GHOSTLIGHT_ATLAS_STAMP="$stamp")
|
||||||
|
for kv in "${sets[@]}"; do env_args+=(--setenv="$kv"); done
|
||||||
|
[ -n "$turns" ] && env_args+=(--setenv=GHOSTLIGHT_PLAYTEST_TURNS="$turns")
|
||||||
|
[ -n "$worlds" ] && env_args+=(--setenv=GHOSTLIGHT_PLAYTEST_WORLDS="$worlds")
|
||||||
|
[ -n "$wall" ] && env_args+=(--setenv=GHOSTLIGHT_PLAYTEST_WALL_MINUTES="$wall")
|
||||||
|
[ -n "${GHOSTLIGHT_CONTROLLER_MAX_CONCURRENT:-}" ] && env_args+=(--setenv=GHOSTLIGHT_CONTROLLER_MAX_CONCURRENT="$GHOSTLIGHT_CONTROLLER_MAX_CONCURRENT")
|
||||||
|
|
||||||
|
sudo systemd-run --unit "$unit" --collect --quiet \
|
||||||
|
-p User="$(id -un)" -p LoadCredential=connector-key:"$KEY" \
|
||||||
|
-p StandardOutput=append:"$out/$stamp.run.log" -p StandardError=append:"$out/$stamp.run.log" \
|
||||||
|
"${env_args[@]}" \
|
||||||
|
"$bin" --ignored --exact "$test_name" --nocapture --test-threads=1
|
||||||
|
|
||||||
|
echo "unit: $unit"
|
||||||
|
echo "output: $out/$stamp"
|
||||||
|
echo "run log: $out/$stamp.run.log"
|
||||||
|
echo "progress: tail -f $out/$stamp/progress.log"
|
||||||
|
echo "status: systemctl status $unit"
|
||||||
1558
sidecar/claude-sdk/package-lock.json
generated
1558
sidecar/claude-sdk/package-lock.json
generated
File diff suppressed because it is too large
Load diff
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue