Import Ghostlight c43eb54 synchronous kernel set as native/aetherlight
Verbatim copy of lib, action, clock, journal, grammar (+tests), lens, cover, import_key_tests, patch (lines 1-6059 and 7906-9606) and the base_world fixtures, with the pruned Cargo.toml/Cargo.lock and a gitignore line for the target dir. native/aetherlight/.gitattributes pins `-text` so the verbatim bytes survive autocrlf checkouts. lib.rs still names the leave-set modules, so this commit does not build; the next commit makes it compile. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
a3c492d54f
commit
5ea472fce2
17 changed files with 37009 additions and 0 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -113,3 +113,4 @@ tests/_scratch_*
|
|||
|
||||
# Stryker.NET mutation reports (regenerated per run)
|
||||
StrykerOutput/
|
||||
native/aetherlight/target/
|
||||
|
|
|
|||
2
native/aetherlight/.gitattributes
vendored
Normal file
2
native/aetherlight/.gitattributes
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
# Verbatim fork of Ghostlight: bytes are the contract (digests, fixtures). No newline conversion.
|
||||
* -text
|
||||
794
native/aetherlight/Cargo.lock
generated
Normal file
794
native/aetherlight/Cargo.lock
generated
Normal file
|
|
@ -0,0 +1,794 @@
|
|||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "aetherlight"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"cultcache-rs",
|
||||
"rmp-serde",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"tempfile",
|
||||
"thiserror",
|
||||
"unicode-normalization",
|
||||
"unicode-properties",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "android_system_properties"
|
||||
version = "0.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anyhow"
|
||||
version = "1.0.104"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
|
||||
|
||||
[[package]]
|
||||
name = "autocfg"
|
||||
version = "1.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.10.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bumpalo"
|
||||
version = "3.20.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "509591b7bcd67f4ef775afad7662703b4935daaa6ec0e5605cfb1090b32a2b6d"
|
||||
dependencies = [
|
||||
"find-msvc-tools",
|
||||
"shlex",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
|
||||
|
||||
[[package]]
|
||||
name = "chrono"
|
||||
version = "0.4.45"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"
|
||||
dependencies = [
|
||||
"iana-time-zone",
|
||||
"js-sys",
|
||||
"num-traits",
|
||||
"serde",
|
||||
"wasm-bindgen",
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "core-foundation-sys"
|
||||
version = "0.8.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crypto-common"
|
||||
version = "0.1.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
"typenum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cultcache-rs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/GameCult/CultLib.git?rev=85f7024a35ea42cf9f0a0199a064526427150191#85f7024a35ea42cf9f0a0199a064526427150191"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"chrono",
|
||||
"cultcache-rs-derive",
|
||||
"fs2",
|
||||
"redb",
|
||||
"rmp-serde",
|
||||
"serde",
|
||||
"serde_bytes",
|
||||
"serde_json",
|
||||
"uuid",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cultcache-rs-derive"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/GameCult/CultLib.git?rev=85f7024a35ea42cf9f0a0199a064526427150191#85f7024a35ea42cf9f0a0199a064526427150191"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.10.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
dependencies = [
|
||||
"block-buffer",
|
||||
"crypto-common",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "errno"
|
||||
version = "0.3.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fastrand"
|
||||
version = "2.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
|
||||
|
||||
[[package]]
|
||||
name = "find-msvc-tools"
|
||||
version = "0.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d45db016d36b838f563236e9193d0ee6ce38f3f68b6c94e914b4929c96bbb890"
|
||||
|
||||
[[package]]
|
||||
name = "fs2"
|
||||
version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"winapi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "futures-core"
|
||||
version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
|
||||
|
||||
[[package]]
|
||||
name = "futures-task"
|
||||
version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
|
||||
|
||||
[[package]]
|
||||
name = "futures-util"
|
||||
version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"futures-task",
|
||||
"pin-project-lite",
|
||||
"slab",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "generic-array"
|
||||
version = "0.14.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
|
||||
dependencies = [
|
||||
"typenum",
|
||||
"version_check",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"r-efi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "iana-time-zone"
|
||||
version = "0.1.65"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"
|
||||
dependencies = [
|
||||
"android_system_properties",
|
||||
"core-foundation-sys",
|
||||
"iana-time-zone-haiku",
|
||||
"js-sys",
|
||||
"log",
|
||||
"wasm-bindgen",
|
||||
"windows-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "iana-time-zone-haiku"
|
||||
version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
|
||||
dependencies = [
|
||||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
||||
|
||||
[[package]]
|
||||
name = "js-sys"
|
||||
version = "0.3.104"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0e0c1080212aad755ea003d18543e8768dd432c48819efd73a7bf1e39b7a5a3a"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"futures-util",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.189"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
|
||||
|
||||
[[package]]
|
||||
name = "linux-raw-sys"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
|
||||
|
||||
[[package]]
|
||||
name = "log"
|
||||
version = "0.4.33"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.21.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||
|
||||
[[package]]
|
||||
name = "pin-project-lite"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "r-efi"
|
||||
version = "6.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
|
||||
|
||||
[[package]]
|
||||
name = "redb"
|
||||
version = "4.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8e925444704b5f17d32bf42f5b6e2df050bceebc3dcd6e71cc73dafe8092e839"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rmp"
|
||||
version = "0.8.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4ba8be72d372b2c9b35542551678538b562e7cf86c3315773cae48dfbfe7790c"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rmp-serde"
|
||||
version = "1.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72f81bee8c8ef9b577d1681a70ebbc962c232461e397b22c208c43c04b67a155"
|
||||
dependencies = [
|
||||
"rmp",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustix"
|
||||
version = "1.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustversion"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_bytes"
|
||||
version = "0.11.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_core"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
version = "1.0.151"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"memchr",
|
||||
"serde",
|
||||
"serde_core",
|
||||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha2"
|
||||
version = "0.10.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures",
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "shlex"
|
||||
version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
|
||||
|
||||
[[package]]
|
||||
name = "slab"
|
||||
version = "0.4.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.119"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tempfile"
|
||||
version = "3.27.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
"getrandom",
|
||||
"once_cell",
|
||||
"rustix",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "2.0.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f"
|
||||
dependencies = [
|
||||
"thiserror-impl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror-impl"
|
||||
version = "2.0.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tinyvec"
|
||||
version = "1.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bb4ebadaa0af04fab11ae01eb5f9fdb5f9c5b875506e210e71c07873528baa7f"
|
||||
dependencies = [
|
||||
"tinyvec_macros",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tinyvec_macros"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
|
||||
|
||||
[[package]]
|
||||
name = "typenum"
|
||||
version = "1.20.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.24"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-normalization"
|
||||
version = "0.1.25"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8"
|
||||
dependencies = [
|
||||
"tinyvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-properties"
|
||||
version = "0.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d"
|
||||
|
||||
[[package]]
|
||||
name = "uuid"
|
||||
version = "1.24.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2cefc03fd367c0c6d4305de1b312cf00248c4114f4a0418ce6a6af769e3b0bd9"
|
||||
dependencies = [
|
||||
"getrandom",
|
||||
"js-sys",
|
||||
"serde_core",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "version_check"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen"
|
||||
version = "0.2.127"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1b70935747edd64d89de3efa29d73789b806c15798f8e7dca4d8ac356b50ce70"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"once_cell",
|
||||
"rustversion",
|
||||
"wasm-bindgen-macro",
|
||||
"wasm-bindgen-shared",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-macro"
|
||||
version = "0.2.127"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77775f8f3f7217702089053b94958f8f54061a3f663417df76e19cbdcca29bc1"
|
||||
dependencies = [
|
||||
"quote",
|
||||
"wasm-bindgen-macro-support",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-macro-support"
|
||||
version = "0.2.127"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e11d33f857dc2fb11b8bc75aee111aa9cbeb12cd9f25efd3d4c2a3dd4e235284"
|
||||
dependencies = [
|
||||
"bumpalo",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
"wasm-bindgen-shared",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-shared"
|
||||
version = "0.2.127"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7ef64dbcc55df09c7e5a46182d181c2cfa3e925f3da937ea764728b4bbb9dcbf"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winapi"
|
||||
version = "0.3.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
|
||||
dependencies = [
|
||||
"winapi-i686-pc-windows-gnu",
|
||||
"winapi-x86_64-pc-windows-gnu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winapi-i686-pc-windows-gnu"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
|
||||
|
||||
[[package]]
|
||||
name = "winapi-x86_64-pc-windows-gnu"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
|
||||
|
||||
[[package]]
|
||||
name = "windows-core"
|
||||
version = "0.62.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
|
||||
dependencies = [
|
||||
"windows-implement",
|
||||
"windows-interface",
|
||||
"windows-link",
|
||||
"windows-result",
|
||||
"windows-strings",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-implement"
|
||||
version = "0.60.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-interface"
|
||||
version = "0.59.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||
|
||||
[[package]]
|
||||
name = "windows-result"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-strings"
|
||||
version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.59.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
|
||||
dependencies = [
|
||||
"windows-targets",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.61.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-targets"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
|
||||
dependencies = [
|
||||
"windows_aarch64_gnullvm",
|
||||
"windows_aarch64_msvc",
|
||||
"windows_i686_gnu",
|
||||
"windows_i686_gnullvm",
|
||||
"windows_i686_msvc",
|
||||
"windows_x86_64_gnu",
|
||||
"windows_x86_64_gnullvm",
|
||||
"windows_x86_64_msvc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_gnullvm"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_msvc"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_gnu"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_gnullvm"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_msvc"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnu"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnullvm"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_msvc"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
|
||||
|
||||
[[package]]
|
||||
name = "zmij"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
||||
24
native/aetherlight/Cargo.toml
Normal file
24
native/aetherlight/Cargo.toml
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
[package]
|
||||
name = "aetherlight"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "MIT"
|
||||
publish = false
|
||||
|
||||
# Its own workspace: the crate builds on its own, outside any parent manifest.
|
||||
[workspace]
|
||||
|
||||
[dependencies]
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "85f7024a35ea42cf9f0a0199a064526427150191", package = "cultcache-rs" }
|
||||
rmp-serde = "1.3"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
sha2 = "0.10"
|
||||
thiserror = "2"
|
||||
unicode-normalization = "0.1.25"
|
||||
unicode-properties = "0.1.4"
|
||||
uuid = { version = "1", features = ["v4", "serde"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
2858
native/aetherlight/src/action.rs
Normal file
2858
native/aetherlight/src/action.rs
Normal file
File diff suppressed because it is too large
Load diff
213
native/aetherlight/src/clock.rs
Normal file
213
native/aetherlight/src/clock.rs
Normal file
|
|
@ -0,0 +1,213 @@
|
|||
//! The world clock and the motion one tick produces.
|
||||
//!
|
||||
//! One entry point into the reducer, [`derive_motion`], reached from `reduce`'s
|
||||
//! `AdvanceTime` arm and from `apply_effect`'s `TimeAdvanced` arm, so a forged
|
||||
//! tick is re-derived by the same function that produced the honest one. It is
|
||||
//! pure over `(state, to)`: no wall clock, no entropy, no caller value beyond
|
||||
//! the span.
|
||||
|
||||
use super::patch::{Commitment, CommitmentKey, CommitmentKind, DependencyTarget, MAX_ROUTE_COST};
|
||||
use super::{PressureMagnitude, PressureSource, SubjectId, WorldState, action, is_retired};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// Minutes since genesis. Monotonic, kernel-owned, world-level. `u64` because a
|
||||
/// world clock has no bound; `Cost` is `1..=MAX_ROUTE_COST` because it weighs
|
||||
/// one edge, and reusing it here would put an edge's bound on the world's age.
|
||||
#[derive(
|
||||
Clone, Copy, Debug, Default, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash,
|
||||
)]
|
||||
#[serde(transparent)]
|
||||
pub struct FictionalMinutes(pub u64);
|
||||
|
||||
impl FictionalMinutes {
|
||||
pub(crate) fn checked_add(self, span: TickMinutes) -> Option<Self> {
|
||||
self.0.checked_add(u64::from(span.0)).map(Self)
|
||||
}
|
||||
|
||||
/// Minutes elapsed since an earlier reading. Saturating because the caller
|
||||
/// is the attention order, which reads a stamp `verify_state_shape` already
|
||||
/// holds to `<= now`.
|
||||
pub(crate) fn since(self, earlier: Self) -> u64 {
|
||||
self.0.saturating_sub(earlier.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// The span one `AdvanceTime` names. Constructor-checked `1..=MAX_ROUTE_COST`
|
||||
/// (one year of minutes), reusing pass 2's constant as a span bound rather than
|
||||
/// an edge bound: an unbounded span lets one command jump the clock past every
|
||||
/// due date in the world and makes the size of a commit a caller-chosen number.
|
||||
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
#[serde(transparent)]
|
||||
pub struct TickMinutes(u32);
|
||||
|
||||
impl TickMinutes {
|
||||
pub fn new(minutes: u32) -> Option<Self> {
|
||||
(1..=MAX_ROUTE_COST)
|
||||
.contains(&minutes)
|
||||
.then_some(Self(minutes))
|
||||
}
|
||||
|
||||
pub fn minutes(self) -> u32 {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Everything one tick moves, stated as outcomes rather than deltas so the
|
||||
/// effect says what the world became.
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Motion {
|
||||
/// Routines that fulfilled, in `(subject, key)` order.
|
||||
pub(crate) fulfilled: Vec<RoutineFulfilled>,
|
||||
/// Pressure rows written, in `(target, source)` order, with the resulting
|
||||
/// magnitude — not the delta.
|
||||
pub(crate) pressed: Vec<PressureWritten>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct RoutineFulfilled {
|
||||
pub(crate) subject: SubjectId,
|
||||
pub(crate) key: CommitmentKey,
|
||||
pub(crate) next_due: FictionalMinutes,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct PressureWritten {
|
||||
pub(crate) target: SubjectId,
|
||||
pub(crate) source: PressureSource,
|
||||
pub(crate) magnitude: PressureMagnitude,
|
||||
}
|
||||
|
||||
/// The whole magnitude policy, in one place, with no per-world tuning. A
|
||||
/// blocked routine raises none at all: it retries on the next tick, which is
|
||||
/// what keeps an unattended subject free of spurious pressure.
|
||||
mod step {
|
||||
pub(super) const OBLIGATION_PAST_DUE: u32 = 1;
|
||||
pub(super) const GOAL_PAST_DUE: u32 = 1;
|
||||
pub(super) const DEPENDENCY_UNAVAILABLE: u32 = 1;
|
||||
}
|
||||
|
||||
/// Three stages, each reading only committed `state` and `to`. No stage sees
|
||||
/// another stage's writes, which is what makes this a one-pass total function
|
||||
/// with no ordering hazard and no partial state to reason about.
|
||||
///
|
||||
/// Pressure accrues per command, not per minute: one thousand one-minute ticks
|
||||
/// and one thousand-minute tick over the same span produce different
|
||||
/// magnitudes. The kernel stays an exact function of the command sequence, and
|
||||
/// the tick cadence is one operational constant in `runtime.rs`.
|
||||
pub(super) fn derive_motion(state: &WorldState, to: FictionalMinutes) -> Motion {
|
||||
let mut fulfilled = Vec::new();
|
||||
let mut pressed: BTreeMap<(SubjectId, PressureSource), u32> = BTreeMap::new();
|
||||
|
||||
for (subject, held) in &state.commitments {
|
||||
// A retired subject cannot act, and neither fulfilling a routine nor
|
||||
// pressing an obligation or goal is anything but that subject acting:
|
||||
// its commitments stay in history, un-discharged and un-deleted, but
|
||||
// the clock stops moving them the moment they are its.
|
||||
if is_retired(state, *subject) {
|
||||
continue;
|
||||
}
|
||||
for (key, commitment) in held {
|
||||
if commitment.due > to {
|
||||
continue;
|
||||
}
|
||||
match commitment.kind {
|
||||
CommitmentKind::Routine => {
|
||||
if let Some(next_due) = routine_rolls(state, *subject, commitment) {
|
||||
fulfilled.push(RoutineFulfilled {
|
||||
subject: *subject,
|
||||
key: *key,
|
||||
next_due,
|
||||
});
|
||||
}
|
||||
}
|
||||
CommitmentKind::Obligation | CommitmentKind::Goal => {
|
||||
let step = if commitment.kind == CommitmentKind::Obligation {
|
||||
step::OBLIGATION_PAST_DUE
|
||||
} else {
|
||||
step::GOAL_PAST_DUE
|
||||
};
|
||||
let source = PressureSource::Commitment {
|
||||
subject: *subject,
|
||||
key: *key,
|
||||
};
|
||||
*pressed.entry((*subject, source)).or_default() += step;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (subject, targets) in &state.dependencies {
|
||||
if is_retired(state, *subject) {
|
||||
continue;
|
||||
}
|
||||
for target in targets {
|
||||
if dependency_unavailable(state, *subject, *target) {
|
||||
let source = PressureSource::Dependency(*target);
|
||||
*pressed.entry((*subject, source)).or_default() += step::DEPENDENCY_UNAVAILABLE;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Motion {
|
||||
fulfilled,
|
||||
pressed: pressed
|
||||
.into_iter()
|
||||
.map(|((target, source), step)| PressureWritten {
|
||||
target,
|
||||
source,
|
||||
magnitude: PressureMagnitude(
|
||||
state
|
||||
.pressures
|
||||
.get(&target)
|
||||
.and_then(|held| held.get(&source))
|
||||
.map_or(0, |magnitude| magnitude.0)
|
||||
.saturating_add(step),
|
||||
),
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A routine fulfils when every one of its checks holds, and its `due` then
|
||||
/// rolls forward by exactly one period per command. Catch-up arithmetic would
|
||||
/// make the number of fulfilments a function of the operator's tick cadence in
|
||||
/// a second place; one roll converges over subsequent ticks.
|
||||
fn routine_rolls(
|
||||
state: &WorldState,
|
||||
subject: SubjectId,
|
||||
commitment: &Commitment,
|
||||
) -> Option<FictionalMinutes> {
|
||||
if !action::preconditions_hold(state, subject, &commitment.checks).is_empty() {
|
||||
return None;
|
||||
}
|
||||
commitment.due.checked_add(commitment.period?)
|
||||
}
|
||||
|
||||
/// Whether a subject's dependency is currently failing it. A closed route is a
|
||||
/// supply failure; an unusable one is a permission question, and reading
|
||||
/// authority here would drag `effective_authority` into every tick for every
|
||||
/// dependency in the world.
|
||||
pub(super) fn dependency_unavailable(
|
||||
state: &WorldState,
|
||||
subject: SubjectId,
|
||||
target: DependencyTarget,
|
||||
) -> bool {
|
||||
match target {
|
||||
DependencyTarget::Route(edge_id) => !state
|
||||
.edges
|
||||
.get(&edge_id)
|
||||
.is_some_and(super::EdgeRecord::is_open),
|
||||
// Absence is zero, per pass 3: the depender holds none of what it
|
||||
// depends on.
|
||||
DependencyTarget::Resource(entity_id) => !state
|
||||
.holdings
|
||||
.get(&subject)
|
||||
.is_some_and(|held| held.contains_key(&entity_id)),
|
||||
// The subject it depends on is nowhere in the world's topology.
|
||||
DependencyTarget::Subject(other) => !state.positions.contains_key(&other),
|
||||
}
|
||||
}
|
||||
1105
native/aetherlight/src/cover.rs
Normal file
1105
native/aetherlight/src/cover.rs
Normal file
File diff suppressed because it is too large
Load diff
209
native/aetherlight/src/grammar.rs
Normal file
209
native/aetherlight/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
native/aetherlight/src/grammar/tests.rs
Normal file
745
native/aetherlight/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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
752
native/aetherlight/src/import_key_tests.rs
Normal file
752
native/aetherlight/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"
|
||||
);
|
||||
}
|
||||
2990
native/aetherlight/src/journal.rs
Normal file
2990
native/aetherlight/src/journal.rs
Normal file
File diff suppressed because it is too large
Load diff
379
native/aetherlight/src/lens.rs
Normal file
379
native/aetherlight/src/lens.rs
Normal file
|
|
@ -0,0 +1,379 @@
|
|||
//! The stock lenses. A lens is the flavor an elaborator session reaches for:
|
||||
//! prompt emphasis over the one fixed tool catalog, never admission, authority,
|
||||
//! or quota. This module owns the stock table, each lens's instruction text,
|
||||
//! and the draw recipe; it reads no world state and writes nothing.
|
||||
|
||||
use super::{CommandId, KernelError, WorldId, digest};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// The sentence every lens's instructions begin with.
|
||||
const ELABORATION_INSTRUCTIONS: &str = "Use only the supplied tools to author structure inside your jurisdiction. Answer the boundary or deficit you were given, then submit. Recording a gap changes nothing.";
|
||||
|
||||
/// The library's stock lens set. Serialized by snake_case name, so a name the
|
||||
/// library does not know cannot be represented at any deserialization boundary.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Lens {
|
||||
Patina,
|
||||
Charter,
|
||||
Ledger,
|
||||
Hearth,
|
||||
Tangle,
|
||||
Veil,
|
||||
Ember,
|
||||
Numen,
|
||||
}
|
||||
|
||||
impl Lens {
|
||||
/// Every lens, in declaration order. The draw walks this order.
|
||||
pub const ALL: [Lens; 8] = [
|
||||
Lens::Patina,
|
||||
Lens::Charter,
|
||||
Lens::Ledger,
|
||||
Lens::Hearth,
|
||||
Lens::Tangle,
|
||||
Lens::Veil,
|
||||
Lens::Ember,
|
||||
Lens::Numen,
|
||||
];
|
||||
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Lens::Patina => "Patina",
|
||||
Lens::Charter => "Charter",
|
||||
Lens::Ledger => "Ledger",
|
||||
Lens::Hearth => "Hearth",
|
||||
Lens::Tangle => "Tangle",
|
||||
Lens::Veil => "Veil",
|
||||
Lens::Ember => "Ember",
|
||||
Lens::Numen => "Numen",
|
||||
}
|
||||
}
|
||||
|
||||
/// What kind of structure the lens reaches for.
|
||||
pub(crate) fn reaches_for(self) -> &'static str {
|
||||
match self {
|
||||
Lens::Patina => "ordinary objects, customs, nicknames, local jokes",
|
||||
Lens::Charter => "government, law, offices, selection, succession, redress",
|
||||
Lens::Ledger => "resources, labor, trade, infrastructure, scarcity, class pressure",
|
||||
Lens::Hearth => "kinship, daily life, care, obligation, belonging",
|
||||
Lens::Tangle => "factions, alliances, rivalries, leverage",
|
||||
Lens::Veil => "secrets, rumors, misinformation, taboos, unevenly held knowledge",
|
||||
Lens::Ember => "disputes, hazards, instability, escalation, urgent pressure",
|
||||
Lens::Numen => "religion, magic, ritual, awe, cosmology, the genuinely strange",
|
||||
}
|
||||
}
|
||||
|
||||
/// Existing `PATCH_TOOLS` names in emphasis order. Emphasis is prompt text
|
||||
/// only: the catalog, its order, and its schemas are the same for every lens.
|
||||
pub(crate) fn leads_with(self) -> &'static [&'static str] {
|
||||
match self {
|
||||
Lens::Patina => &[
|
||||
"set_persona_material",
|
||||
"declare_affordance",
|
||||
"declare_resource",
|
||||
"declare_place",
|
||||
],
|
||||
Lens::Charter => &[
|
||||
"grant_authority",
|
||||
"open_office",
|
||||
"install_incumbent",
|
||||
"open_forum",
|
||||
"declare_subject",
|
||||
],
|
||||
Lens::Ledger => &[
|
||||
"transfer",
|
||||
"bind",
|
||||
"declare_resource",
|
||||
"alter_cost",
|
||||
"declare_route",
|
||||
],
|
||||
Lens::Hearth => &[
|
||||
"create_commitment",
|
||||
"set_persona_material",
|
||||
"declare_subject",
|
||||
],
|
||||
Lens::Tangle => &[
|
||||
"advance_pressure",
|
||||
"create_commitment",
|
||||
"grant_authority",
|
||||
"declare_subject",
|
||||
"bind",
|
||||
],
|
||||
Lens::Veil => &[
|
||||
"acquire_knowledge",
|
||||
"communicate",
|
||||
"declare_channel",
|
||||
"set_reach",
|
||||
"declare_fact",
|
||||
"forget",
|
||||
],
|
||||
Lens::Ember => &[
|
||||
"advance_pressure",
|
||||
"create_commitment",
|
||||
"close_route",
|
||||
"consume",
|
||||
],
|
||||
Lens::Numen => &[
|
||||
"declare_fact",
|
||||
"declare_affordance",
|
||||
"set_persona_material",
|
||||
"witness",
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
/// The elaborator's instructions under this lens: the shared sentence, then
|
||||
/// the lens clause. Read once, when a session is first built; the session
|
||||
/// then carries the text, and nothing rebuilds it from here.
|
||||
pub(crate) fn instructions(self) -> String {
|
||||
format!(
|
||||
"{ELABORATION_INSTRUCTIONS} Lens: {}. Reach for {}. Lead with {}; every supplied tool remains available.",
|
||||
self.name(),
|
||||
self.reaches_for(),
|
||||
self.leads_with().join(", "),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// A world's lens weights. Validity is decided where weights are admitted;
|
||||
/// `Default` is the empty map a world holds before genesis writes its weights,
|
||||
/// and it never draws.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct LensWeights(BTreeMap<Lens, u32>);
|
||||
|
||||
impl LensWeights {
|
||||
pub fn new(weights: BTreeMap<Lens, u32>) -> Self {
|
||||
Self(weights)
|
||||
}
|
||||
|
||||
/// A lens the map does not name weighs zero.
|
||||
pub fn get(&self, lens: Lens) -> u32 {
|
||||
self.0.get(&lens).copied().unwrap_or(0)
|
||||
}
|
||||
|
||||
pub fn iter(&self) -> impl Iterator<Item = (Lens, u32)> + '_ {
|
||||
self.0.iter().map(|(lens, weight)| (*lens, *weight))
|
||||
}
|
||||
|
||||
/// Some weight is nonzero, so a draw has somewhere to land.
|
||||
pub(crate) fn draws(&self) -> bool {
|
||||
self.0.values().any(|weight| *weight > 0)
|
||||
}
|
||||
|
||||
/// Every stock lens weighs the same in both sets. A lens a map does not
|
||||
/// name weighs zero, so `{charter: 3}` and `{patina: 0, charter: 3}` are
|
||||
/// one set spelled two ways: they draw identically and neither replaces
|
||||
/// the other.
|
||||
pub(crate) fn weighs_the_same_as(&self, other: &LensWeights) -> bool {
|
||||
Lens::ALL
|
||||
.into_iter()
|
||||
.all(|lens| self.get(lens) == other.get(lens))
|
||||
}
|
||||
}
|
||||
|
||||
/// The draw's whole input: the world and the session's fixed identity. The
|
||||
/// weights select over it; they are not part of it.
|
||||
#[derive(Serialize)]
|
||||
struct LensPreimage {
|
||||
world_id: WorldId,
|
||||
command_id: CommandId,
|
||||
}
|
||||
|
||||
/// One digest, one modulo, one cumulative walk over `Lens::ALL` — the recipe
|
||||
/// `select_band` uses, not a second entropy shape. The same world, session
|
||||
/// identity, and weights draw the same lens. Modulo rather than rejection
|
||||
/// sampling: the bias is bounded by `total_weight / 2^64`.
|
||||
pub(crate) fn draw(
|
||||
weights: &LensWeights,
|
||||
world_id: WorldId,
|
||||
command_id: CommandId,
|
||||
) -> Result<Lens, KernelError> {
|
||||
// The guard is on the divisor itself, as `select_band`'s is: no other
|
||||
// statement of "these weights draw" can let the modulo below divide by zero.
|
||||
let total: u128 = Lens::ALL
|
||||
.iter()
|
||||
.map(|lens| u128::from(weights.get(*lens)))
|
||||
.sum();
|
||||
if total == 0 {
|
||||
return Err(KernelError::Invariant("lens weights never draw".into()));
|
||||
}
|
||||
let preimage = digest(&LensPreimage {
|
||||
world_id,
|
||||
command_id,
|
||||
})?;
|
||||
let head = preimage
|
||||
.strip_prefix("sha256:")
|
||||
.and_then(|hex| hex.get(..16))
|
||||
.and_then(|head| u64::from_str_radix(head, 16).ok())
|
||||
.ok_or_else(|| KernelError::Invariant("lens draw digest is not hex".into()))?;
|
||||
let mut position = u128::from(head) % total;
|
||||
for lens in Lens::ALL {
|
||||
let weight = u128::from(weights.get(lens));
|
||||
if position < weight {
|
||||
return Ok(lens);
|
||||
}
|
||||
position -= weight;
|
||||
}
|
||||
Err(KernelError::Invariant(
|
||||
"lens weights did not cover the draw".into(),
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::patch::PATCH_TOOLS;
|
||||
use crate::tests::stock_weights;
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
fn ids() -> Vec<CommandId> {
|
||||
(0..200)
|
||||
.map(|i| CommandId::derived("l1-probe", &[&i.to_string()]))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn tally(weights: &LensWeights) -> BTreeMap<Lens, usize> {
|
||||
let mut counts = BTreeMap::new();
|
||||
for id in ids() {
|
||||
let lens = draw(weights, WorldId::nil_for_test(), id).unwrap();
|
||||
*counts.entry(lens).or_insert(0) += 1;
|
||||
}
|
||||
counts
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_lead_names_a_patch_tool() {
|
||||
let catalog: BTreeSet<&str> = PATCH_TOOLS.iter().map(|entry| entry.name).collect();
|
||||
for lens in Lens::ALL {
|
||||
let leads = lens.leads_with();
|
||||
assert!(!leads.is_empty(), "{lens:?} leads with nothing");
|
||||
let distinct: BTreeSet<&str> = leads.iter().copied().collect();
|
||||
assert_eq!(distinct.len(), leads.len(), "{lens:?} repeats a lead");
|
||||
for name in leads {
|
||||
assert!(
|
||||
catalog.contains(name),
|
||||
"{lens:?} leads with unknown tool {name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_draw_is_a_function_of_world_and_session() {
|
||||
let weights = stock_weights();
|
||||
let world = WorldId::nil_for_test();
|
||||
for id in ids() {
|
||||
assert_eq!(
|
||||
draw(&weights, world, id).unwrap(),
|
||||
draw(&weights, world, id).unwrap()
|
||||
);
|
||||
}
|
||||
let expected: BTreeMap<Lens, usize> = BTREE_STOCK_TALLY.into_iter().collect();
|
||||
assert_eq!(tally(&weights), expected);
|
||||
}
|
||||
|
||||
/// Computed at Cut 1 and pinned: the replay proof for 200 derived ids under
|
||||
/// stock weights.
|
||||
const BTREE_STOCK_TALLY: [(Lens, usize); 8] = [
|
||||
(Lens::Patina, 22),
|
||||
(Lens::Charter, 37),
|
||||
(Lens::Ledger, 26),
|
||||
(Lens::Hearth, 19),
|
||||
(Lens::Tangle, 23),
|
||||
(Lens::Veil, 29),
|
||||
(Lens::Ember, 18),
|
||||
(Lens::Numen, 26),
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn a_zero_weight_never_draws() {
|
||||
let weights = LensWeights::new(BTreeMap::from([
|
||||
(Lens::Patina, 0),
|
||||
(Lens::Charter, 3),
|
||||
(Lens::Ledger, 1),
|
||||
]));
|
||||
let counts = tally(&weights);
|
||||
assert_eq!(counts.get(&Lens::Patina), None, "a zero weight drew");
|
||||
let expected: BTreeMap<Lens, usize> = ZERO_WEIGHT_TALLY.into_iter().collect();
|
||||
assert_eq!(counts, expected);
|
||||
}
|
||||
|
||||
/// Computed at Cut 1 and pinned; near 3:1 over the same 200 ids.
|
||||
const ZERO_WEIGHT_TALLY: [(Lens, usize); 2] = [(Lens::Charter, 155), (Lens::Ledger, 45)];
|
||||
|
||||
#[test]
|
||||
fn all_zero_weights_are_an_error() {
|
||||
let world = WorldId::nil_for_test();
|
||||
let id = CommandId::derived("l1-probe", &["0"]);
|
||||
let all_zero = LensWeights::new(Lens::ALL.into_iter().map(|lens| (lens, 0)).collect());
|
||||
assert_eq!(all_zero.iter().count(), 8);
|
||||
for weights in [LensWeights::default(), all_zero] {
|
||||
assert!(matches!(
|
||||
draw(&weights, world, id),
|
||||
Err(KernelError::Invariant(_))
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_lens_name_does_not_deserialize() {
|
||||
for refused in [
|
||||
r#"{"Patina":1}"#,
|
||||
r#"{"patina ":1}"#,
|
||||
r#"{"patinaa":1}"#,
|
||||
r#"{"patina":1,"tribunal":1}"#,
|
||||
] {
|
||||
assert!(
|
||||
serde_json::from_str::<LensWeights>(refused).is_err(),
|
||||
"{refused} deserialized"
|
||||
);
|
||||
}
|
||||
let accepted = serde_json::from_str::<LensWeights>(r#"{"patina":1}"#).unwrap();
|
||||
assert_eq!(accepted.get(Lens::Patina), 1);
|
||||
assert_eq!(accepted.iter().count(), 1);
|
||||
|
||||
let stock = stock_weights();
|
||||
let bytes = rmp_serde::to_vec_named(&stock).unwrap();
|
||||
let back: LensWeights = rmp_serde::from_slice(&bytes).unwrap();
|
||||
assert_eq!(back, stock);
|
||||
assert_eq!(rmp_serde::to_vec_named(&back).unwrap(), bytes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_lens_text_names_its_own_leads() {
|
||||
let mut texts = BTreeSet::new();
|
||||
for lens in Lens::ALL {
|
||||
let text = lens.instructions();
|
||||
assert!(text.contains(lens.name()), "{lens:?} text omits its name");
|
||||
for name in lens.leads_with() {
|
||||
assert!(text.contains(name), "{lens:?} text omits {name}");
|
||||
}
|
||||
texts.insert(text);
|
||||
}
|
||||
assert_eq!(texts.len(), 8, "two lenses share a text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lenses_serialize_as_snake_case_names() {
|
||||
let names: Vec<String> = Lens::ALL
|
||||
.iter()
|
||||
.map(|lens| serde_json::to_string(lens).unwrap())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
names,
|
||||
[
|
||||
r#""patina""#,
|
||||
r#""charter""#,
|
||||
r#""ledger""#,
|
||||
r#""hearth""#,
|
||||
r#""tangle""#,
|
||||
r#""veil""#,
|
||||
r#""ember""#,
|
||||
r#""numen""#,
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
19173
native/aetherlight/src/lib.rs
Normal file
19173
native/aetherlight/src/lib.rs
Normal file
File diff suppressed because it is too large
Load diff
7760
native/aetherlight/src/patch.rs
Normal file
7760
native/aetherlight/src/patch.rs
Normal file
File diff suppressed because it is too large
Load diff
BIN
native/aetherlight/tests/fixtures/base_world.cc
vendored
Normal file
BIN
native/aetherlight/tests/fixtures/base_world.cc
vendored
Normal file
Binary file not shown.
3
native/aetherlight/tests/fixtures/base_world.digests
vendored
Normal file
3
native/aetherlight/tests/fixtures/base_world.digests
vendored
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
3
|
||||
sha256:b706f57cb417603366a1f47a5dd099fbf68bfecc5b2e8d61d281630791d1d76d
|
||||
sha256:2039956a26c3d5b073d101e5898ac5a60a9eb63a3b93f447b2d8f78ef4caf979
|
||||
1
native/aetherlight/tests/fixtures/base_world.id
vendored
Normal file
1
native/aetherlight/tests/fixtures/base_world.id
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
"a534b32a-4d00-429c-bf6c-ce1d55385380"
|
||||
Loading…
Reference in a new issue