diff --git a/.gitignore b/.gitignore index ac9c49142..8f15133d1 100644 --- a/.gitignore +++ b/.gitignore @@ -113,3 +113,4 @@ tests/_scratch_* # Stryker.NET mutation reports (regenerated per run) StrykerOutput/ +native/aetherlight/target/ diff --git a/native/aetherlight/.gitattributes b/native/aetherlight/.gitattributes new file mode 100644 index 000000000..14b915993 --- /dev/null +++ b/native/aetherlight/.gitattributes @@ -0,0 +1,2 @@ +# Verbatim fork of Ghostlight: bytes are the contract (digests, fixtures). No newline conversion. +* -text diff --git a/native/aetherlight/Cargo.lock b/native/aetherlight/Cargo.lock new file mode 100644 index 000000000..d79ad2fc6 --- /dev/null +++ b/native/aetherlight/Cargo.lock @@ -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" diff --git a/native/aetherlight/Cargo.toml b/native/aetherlight/Cargo.toml new file mode 100644 index 000000000..ec8f9d37e --- /dev/null +++ b/native/aetherlight/Cargo.toml @@ -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" diff --git a/native/aetherlight/src/action.rs b/native/aetherlight/src/action.rs new file mode 100644 index 000000000..bbfddae96 --- /dev/null +++ b/native/aetherlight/src/action.rs @@ -0,0 +1,2858 @@ +//! The invocation pipeline: catalog lookup, role binding, precondition +//! evaluation, effect-ceiling checking, band selection, and lowering. +//! +//! One entry point, [`exercise`], reached from `reduce`'s `ExerciseDecision` arm +//! and from `apply_effect`'s `DecisionExercised` arm, so a forged effect is +//! re-derived by the same function that produced the honest one. Nothing else +//! draws a band, and the draw goes through the one `digest()` owner. + +use super::patch::{ + self, Affordance, Audience, AudienceSpec, BoundPrecondition, Bounds, ComponentOpKind, Cost, + Precondition, Quantity, RefKind, Role, WorldPatch, +}; +use super::{ + AffordanceId, AuthorityGrant, AuthorityTarget, CommandId, DecisionEvent, DecisionInvocation, + DecisionOpportunity, EdgeId, EntityId, EventId, FictionalMinutes, GrantedAffordance, + KernelError, Magnitude, SubjectId, Target, WorldId, WorldState, digest, +}; +use serde::Serialize; +use std::collections::{BTreeMap, BTreeSet}; + +/// The complete failure set of one affordance invocation. Sorted and complete +/// like `Mismatch`, and like it never serialized: it states the affordance +/// contract, which no commit records. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum ActionMismatch { + UnboundRole { + role: Role, + }, + UnknownRole { + role: Role, + }, + DuplicateRoleBinding { + role: Role, + }, + UnknownTarget { + role: Role, + }, + TargetKindMismatch { + role: Role, + expected: RefKind, + actual: RefKind, + }, + ActorNotPresent { + precondition: usize, + }, + TargetUnreachable { + precondition: usize, + }, + InsufficientHolding { + precondition: usize, + }, + SlotNotProposed { + slot: usize, + }, + UnknownSlot { + slot: usize, + }, + DuplicateSlotProposal { + slot: usize, + }, + MagnitudeShapeMismatch { + slot: usize, + }, + MagnitudeOverCeiling { + slot: usize, + }, + ZeroMagnitude { + slot: usize, + }, + SpeechRequired, + SpeechNotCarried, + EmptySpeech, + EmptyDisplay, + /// The acting subject's effective authority covers no such target under + /// this kind. A target that walked out of the jurisdiction while the + /// proposal was in flight arrives here, not as a rebind: what the actor is + /// authorized over is in the digest, the world it reaches is not. + NotAuthorized { + precondition: usize, + }, + /// No forum takes this grievance, or its standing does not reach the actor. + NoStanding { + precondition: usize, + }, + /// An invocation bound the reserved `actor` role. + ActorRoleBound, + /// A slot would grant authority the acting subject does not itself hold + /// over that ground. Without this, any holder mints unlimited authority in + /// one step and the whole component is decorative. + DelegationNotMonotone { + slot: usize, + }, + /// The actor does not hold the bound fact at the required confidence. A + /// re-appraisal that lowered its own confidence while the proposal was in + /// flight arrives here rather than as a rebind: confidence is admission-only. + FactUnknown { + precondition: usize, + }, + /// The actor has no audience at all: unplaced for co-location, or outside a + /// channel it does not control. + NoAudience { + precondition: usize, + }, + /// The addressed subject is not inside that audience. A target that walked + /// out of the room while the proposal was in flight arrives here: the + /// preimage holds what the actor *is*, not the world it reaches. + CannotReach { + precondition: usize, + }, + /// The actor holds no commitment of that kind to the bound referent. + NotCommitted { + precondition: usize, + }, +} + +/// The band draw's whole preimage. Five fields, none of them from the +/// invocation's payload: the proposer varies the attempt and cannot vary the +/// draw. `affordance` is the id carried by the kernel-verified grant, so the +/// draw cannot be steered by an affordance the scope does not hold. +#[derive(Serialize)] +struct BandPreimage { + world_id: WorldId, + revision: u64, + command_id: CommandId, + affordance: AffordanceId, + band_count: usize, +} + +/// Catalog lookup, binding, admission, draw, lowering, event. Stages 1 through 4 +/// accumulate one complete rejection set and return it sorted before anything is +/// drawn or lowered, so nothing past the gate can fail on caller input. +/// +/// The entry arrives as a [`GrantedAffordance`], which only `require_granted` +/// can build: the grant check is the type, not a call a third caller might +/// forget. Nothing here reads `invocation.affordance`. +pub(super) fn exercise( + state: &WorldState, + command_id: CommandId, + current: &DecisionOpportunity, + granted: &GrantedAffordance<'_>, + invocation: &DecisionInvocation, +) -> Result { + let entry = granted.entry; + let actor = current.scope.subject_id; + let mut rejections = Vec::new(); + + let components = super::scope_components(state, actor); + let authority = super::effective_authority(&components.authority, &components.delegated); + let bindings = bind_roles(state, actor, entry, invocation, &mut rejections); + check_preconditions(state, actor, &authority, entry, &bindings, &mut rejections); + check_proposals(entry, invocation, &mut rejections); + check_delegation(state, &authority, entry, &bindings, &mut rejections); + + if !rejections.is_empty() { + rejections.sort(); + return Err(KernelError::ActionRejected(rejections)); + } + + let band = select_band(state, command_id, granted.id, entry)?; + let operations = lower(entry, band, actor, state.now, invocation, &bindings)?; + let mut effects = if operations.is_empty() { + Vec::new() + } else { + // The same resolver, the same per-operation preconditions, the same + // conservation equation the declaration lane passes. + patch::resolve_patch( + state, + command_id, + &WorldPatch { + declarations: Vec::new(), + operations, + evidence: Vec::new(), + }, + None, + None, + ) + .map_err(KernelError::PatchRejected)? + .operations + }; + + // The speech lowering: kernel-owned, not a slot, and unreachable by any + // proposer, band, or effect ceiling. The audience comes from the entry's one + // speech precondition, so a world's `whisper` and `proclaim` lower through + // the same two operations with a different audience and the kernel learns no + // genre. Addressing does not narrow the fan-out: a voice fills its audience. + let speech = match (&invocation.speech, entry.carries_speech) { + (Some(statement), true) => { + let fact = EntityId(patch::derive_id( + patch::ENTITY_NAMESPACE, + state.world_id, + command_id, + &patch::DraftHandle::new(SPEECH_HANDLE), + Some(SPEECH_INDEX), + )); + let to = speech_audience(entry, &bindings)?; + effects.splice( + 0..0, + [ + patch::ResolvedOp::AssertClaim { + fact, + statement: statement.clone(), + by: actor, + }, + patch::ResolvedOp::Communicate { + speaker: actor, + fact, + to, + }, + ], + ); + Some(fact) + } + _ => None, + }; + // The display lowering: the same standing as speech, from the same + // allocation site under the second discriminator. It needs no entry + // field and reads no audience precondition: a body is visible to the room + // whatever the entry addresses, so `proclaim` down a horn still shrugs at + // whoever stands beside the speaker. + let display = invocation.display.as_ref().map(|statement| { + let fact = EntityId(patch::derive_id( + patch::ENTITY_NAMESPACE, + state.world_id, + command_id, + &patch::DraftHandle::new(SPEECH_HANDLE), + Some(DISPLAY_INDEX), + )); + let at = usize::from(speech.is_some()) * 2; + effects.splice( + at..at, + [ + patch::ResolvedOp::AssertClaim { + fact, + statement: statement.clone(), + by: actor, + }, + patch::ResolvedOp::Display { actor, fact }, + ], + ); + fact + }); + + let revision = super::resolution_revision(state)?; + Ok(DecisionEvent { + id: EventId::for_command(command_id), + revision, + scope: current.scope, + controller_id: current.controller_id, + affordance: granted.id, + speech, + display, + band, + effects, + }) +} + +/// The synthetic handle every minted claim allocates under. It is synthesized +/// only in Active and declarations are Draft-only, so no world-declared handle +/// can collide with it. +const SPEECH_HANDLE: &str = "ghostlight.speech"; + +/// The speech index, passed as `derive_id`'s discriminator. It is `0` for every +/// invocation because one invocation carries one utterance; it exists so a +/// second minted claim needs no second allocation idiom. +const SPEECH_INDEX: &str = "0"; + +/// The display index: the second claim one invocation may mint, under the +/// same handle and allocation site as speech. +const DISPLAY_INDEX: &str = "1"; + +/// The audience a speech-carrying entry names. The declaration validator already +/// refused an entry with none (`SpeechWithoutAudience`) or two +/// (`AmbiguousSpeechAudience`), so anything else here is a corrupt catalog. +fn speech_audience( + entry: &Affordance, + bindings: &BTreeMap, +) -> Result { + entry + .preconditions + .iter() + .find_map(|precondition| match precondition { + Precondition::CanBroadcast { via } | Precondition::CanReach { via, .. } => { + bound_audience(via, bindings) + } + _ => None, + }) + .ok_or_else(|| KernelError::Invariant("a speech-carrying entry names no audience".into())) +} + +/// Stage 2. The acting subject is never a declared role: the kernel binds the +/// reserved name `actor` to it and refuses an invocation that tries to. A +/// binding that happens to name the actor through a declared role is legal and +/// unremarkable. +fn bind_roles( + state: &WorldState, + actor: SubjectId, + entry: &Affordance, + invocation: &DecisionInvocation, + rejections: &mut Vec, +) -> BTreeMap { + let declared: BTreeMap<&Role, RefKind> = entry + .roles + .iter() + .map(|spec| (&spec.role, spec.kind)) + .collect(); + let mut bound: BTreeMap = BTreeMap::new(); + let mut seen: BTreeSet<&Role> = BTreeSet::new(); + for binding in &invocation.bindings { + if binding.role.0 == patch::ACTOR_ROLE { + rejections.push(ActionMismatch::ActorRoleBound); + continue; + } + if !seen.insert(&binding.role) { + rejections.push(ActionMismatch::DuplicateRoleBinding { + role: binding.role.clone(), + }); + continue; + } + let Some(expected) = declared.get(&binding.role).copied() else { + rejections.push(ActionMismatch::UnknownRole { + role: binding.role.clone(), + }); + continue; + }; + let Some(actual) = live_kind(state, binding.target) else { + rejections.push(ActionMismatch::UnknownTarget { + role: binding.role.clone(), + }); + continue; + }; + let fits = match (expected, actual) { + (RefKind::Subject(None), RefKind::Subject(_)) => true, + (expected, actual) => expected == actual, + }; + if fits { + bound.insert(binding.role.clone(), binding.target); + } else { + rejections.push(ActionMismatch::TargetKindMismatch { + role: binding.role.clone(), + expected, + actual, + }); + } + } + for spec in &entry.roles { + if !seen.contains(&spec.role) { + rejections.push(ActionMismatch::UnboundRole { + role: spec.role.clone(), + }); + } + } + // The kernel's own binding, added after the caller's so nothing can shadow + // it: a slot that must land on the actor says `actor` and the proposer has + // no say. Without it, a levy's `Transfer` would need the proposer to name + // the payee, and an authorized collector could lawfully take a tax and send + // it to a friend. + bound.insert(Role(patch::ACTOR_ROLE.into()), Target::Subject(actor)); + bound +} + +/// What a target actually is in committed state. `None` means the target keys no +/// live partition in its namespace. +fn live_kind(state: &WorldState, target: Target) -> Option { + match target { + Target::Subject(subject_id) => state + .subjects + .get(&subject_id) + .map(|subject| RefKind::Subject(Some(subject.kind))), + Target::Entity(entity_id) => state + .entities + .get(&entity_id) + .map(|record| RefKind::Entity(record.kind)), + Target::Edge(edge_id) => state + .edges + .get(&edge_id) + .map(|_| RefKind::Edge(patch::EdgeKind::Route)), + } +} + +/// Stage 3, in declaration order, each failure carrying its index so a test can +/// name the exact precondition that refused. Role binding is this caller's job: +/// each declared `Precondition` is lowered through stage 2's bindings into a +/// `BoundPrecondition` and handed to the one evaluator. A precondition whose +/// role stage 2 left unbound is skipped here, because stage 2 already named it. +fn check_preconditions( + state: &WorldState, + actor: SubjectId, + authority: &BTreeSet, + entry: &Affordance, + bindings: &BTreeMap, + rejections: &mut Vec, +) { + for (index, precondition) in entry.preconditions.iter().enumerate() { + let Some(bound) = bind_precondition(precondition, bindings) else { + continue; + }; + if let Some(mismatch) = evaluate(state, actor, authority, index, &bound) { + rejections.push(mismatch); + } + } +} + +/// The catalog's role indirection lowered to canonical referents. `None` means +/// a role is unbound or bound to the wrong namespace, which stage 2 named. +fn bind_precondition( + precondition: &Precondition, + bindings: &BTreeMap, +) -> Option { + let place = |role: &Role| match bindings.get(role)? { + Target::Entity(entity_id) => Some(*entity_id), + _ => None, + }; + Some(match precondition { + Precondition::Present { at } => BoundPrecondition::Present { at: place(at)? }, + Precondition::Reachable { to, within } => BoundPrecondition::Reachable { + to: place(to)?, + within: *within, + }, + Precondition::Holds { resource, at_least } => BoundPrecondition::Holds { + resource: place(resource)?, + at_least: *at_least, + }, + Precondition::Authorized { over, kind } => BoundPrecondition::Authorized { + over: bindings.get(over).copied()?, + kind: kind.clone(), + }, + Precondition::HasStanding { grievance } => BoundPrecondition::HasStanding { + grievance: grievance.clone(), + }, + Precondition::Knows { fact, at_least } => BoundPrecondition::Knows { + fact: place(fact)?, + at_least: *at_least, + }, + Precondition::CanBroadcast { via } => BoundPrecondition::CanBroadcast { + via: bound_audience(via, bindings)?, + }, + Precondition::CanReach { subject, via } => BoundPrecondition::CanReach { + subject: match bindings.get(subject)? { + Target::Subject(subject_id) => *subject_id, + _ => return None, + }, + via: bound_audience(via, bindings)?, + }, + Precondition::Committed { to, kind } => BoundPrecondition::Committed { + to: match bindings.get(to)? { + Target::Subject(subject_id) => *subject_id, + _ => return None, + }, + kind: *kind, + }, + }) +} + +/// The one precondition reader, over referents that are already canonical. +/// Returns the complete set in declaration order; an empty set is "all hold". +/// The tick reads only its emptiness — an `ActionMismatch` never surfaces to +/// anyone from there. +pub(super) fn preconditions_hold( + state: &WorldState, + actor: SubjectId, + checks: &[BoundPrecondition], +) -> Vec { + let components = super::scope_components(state, actor); + let authority = super::effective_authority(&components.authority, &components.delegated); + checks + .iter() + .enumerate() + .filter_map(|(index, check)| evaluate(state, actor, &authority, index, check)) + .collect() +} + +/// One check against committed state. `index` is the position within the slice +/// the caller passed in, which is what every `precondition: usize` means. +fn evaluate( + state: &WorldState, + actor: SubjectId, + authority: &BTreeSet, + index: usize, + check: &BoundPrecondition, +) -> Option { + let holds = match check { + BoundPrecondition::Present { at } => { + return (state.positions.get(&actor).map(|position| position.place) != Some(*at)) + .then_some(ActionMismatch::ActorNotPresent { + precondition: index, + }); + } + BoundPrecondition::Reachable { to, within } => { + return (!reachable(state, actor, authority, *to, *within)).then_some( + ActionMismatch::TargetUnreachable { + precondition: index, + }, + ); + } + BoundPrecondition::Holds { resource, at_least } => { + state + .holdings + .get(&actor) + .and_then(|held| held.get(resource)) + .map_or(0, |quantity| quantity.0) + >= at_least.0 + } + BoundPrecondition::Authorized { over, kind } => { + return (!authority + .iter() + .any(|grant| &grant.kind == kind && super::covers(state, grant.over, *over))) + .then_some(ActionMismatch::NotAuthorized { + precondition: index, + }); + } + BoundPrecondition::HasStanding { grievance } => { + return (!state.redress.get(grievance).is_some_and(|forum| { + super::covers(state, forum.standing, Target::Subject(actor)) + })) + .then_some(ActionMismatch::NoStanding { + precondition: index, + }); + } + BoundPrecondition::Knows { fact, at_least } => { + return (!state + .knowledge + .get(&actor) + .and_then(|held| held.get(fact)) + .is_some_and(|held| held.confidence >= *at_least)) + .then_some(ActionMismatch::FactUnknown { + precondition: index, + }); + } + BoundPrecondition::CanBroadcast { via } => { + return (!super::can_broadcast(state, actor, via)).then_some( + ActionMismatch::NoAudience { + precondition: index, + }, + ); + } + BoundPrecondition::CanReach { subject, via } => { + return (!super::audience(state, actor, via).contains(subject)).then_some( + ActionMismatch::CannotReach { + precondition: index, + }, + ); + } + // A linear scan of one subject's own small map. No key lookup is needed + // and none is offered, which is why a `CommitmentKey` never has to be + // guessable. + BoundPrecondition::Committed { to, kind } => { + return (!state.commitments.get(&actor).is_some_and(|held| { + held.values().any(|commitment| { + commitment.counterparty == Some(*to) && commitment.kind == *kind + }) + })) + .then_some(ActionMismatch::NotCommitted { + precondition: index, + }); + } + }; + (!holds).then_some(ActionMismatch::InsufficientHolding { + precondition: index, + }) +} + +/// The catalog's role indirection lowered to the canonical audience: the entry +/// names a role, the invoker binds a channel to it, and every reader of reach +/// sees one shape. `None` means the role is unbound, which stage 2 already named. +fn bound_audience(via: &AudienceSpec, bindings: &BTreeMap) -> Option { + match via { + AudienceSpec::Colocated => Some(Audience::Colocated), + AudienceSpec::Channel(role) => match bindings.get(role).copied() { + Some(Target::Entity(entity_id)) => Some(Audience::Channel(entity_id)), + _ => None, + }, + } +} + +/// Stage 4, beside the ceilings: an authority a slot would grant or revoke +/// must not exceed the actor's own. For a grant this is the monotonicity +/// envelope — no holder mints authority it does not itself hold. For a +/// revocation it is the same envelope read the other way: an actor may not +/// strip ground it holds no jurisdiction over, so revocation is not a lever +/// for reaching past one's own authority. Every slot is checked, not just the +/// drawn band's, for the same reason every ceiling is — the proposer commits +/// to a complete attempt and cannot see the band. +/// +/// The rule is action-lane only, and that is not two truths. The patch lane's +/// `GrantAuthority`/`RevokeAuthority` is admitted by the world owner; +/// monotonicity *is* the action lane's authority envelope, and both lanes +/// reach one `apply_operation` with the identical mutation. +fn check_delegation( + state: &WorldState, + authority: &BTreeSet, + entry: &Affordance, + bindings: &BTreeMap, + rejections: &mut Vec, +) { + for (index, slot) in entry.effect_slots.iter().enumerate() { + let kind = match &slot.op_kind { + ComponentOpKind::GrantAuthority { kind } + | ComponentOpKind::RevokeAuthority { kind } => kind, + _ => continue, + }; + let Some(over) = slot + .roles + .get(1) + .and_then(|role| bindings.get(role)) + .copied() + .and_then(authority_target_of) + else { + continue; + }; + if !authority.iter().any(|grant| { + &grant.kind == kind && super::covers(state, grant.over, over.as_referent()) + }) { + rejections.push(ActionMismatch::DelegationNotMonotone { slot: index }); + } + } +} + +/// The authority target a bound referent names. A route is jurisdictional +/// ground but never a grant's target, so a slot bound to one lowers to nothing. +fn authority_target_of(target: Target) -> Option { + match target { + Target::Subject(subject_id) => Some(AuthorityTarget::Subject(subject_id)), + Target::Entity(entity_id) => Some(AuthorityTarget::PlaceSubtree(entity_id)), + Target::Edge(_) => None, + } +} + +/// Dijkstra over the live route graph, admitting the open routes this subject +/// may traverse — the same `route_admits` rule the resolver applies to a +/// `Relocate`, so a subject with the right authority can plan a path through +/// its own restricted ground — and +/// relaxing in `EdgeId` order, pruning any path whose accumulated cost exceeds +/// `within`. Cost 0 — already standing there — succeeds; `Present` is the strict +/// form. An unplaced actor reaches nothing. +/// +/// This reads routes the scope digest does not cover, which is deliberate: the +/// alternative binds a proposal to a transitively large slice of world topology +/// and rejects it whenever anything near the actor commits. Admission runs at +/// commit against live state instead, so a route that closed while the proposal +/// was in flight makes this fail rather than letting a stale path commit. +fn reachable( + state: &WorldState, + actor: SubjectId, + authority: &BTreeSet, + destination: EntityId, + within: Cost, +) -> bool { + let Some(origin) = state.positions.get(&actor).map(|position| position.place) else { + return false; + }; + let mut best: BTreeMap = BTreeMap::from([(origin, 0)]); + let mut settled: BTreeSet = BTreeSet::new(); + let ceiling = u64::from(within.0); + loop { + let Some((place, cost)) = best + .iter() + .filter(|(place, _)| !settled.contains(place)) + .min_by_key(|(place, cost)| (**cost, **place)) + .map(|(place, cost)| (*place, *cost)) + else { + return false; + }; + if place == destination { + return true; + } + settled.insert(place); + let outbound: Vec<(EdgeId, EntityId, u64)> = state + .edges + .iter() + .filter(|(_, record)| record.is_open()) + .filter_map(|(edge_id, record)| { + let (from, to) = record.endpoints(); + let next = if from == place { + to + } else if to == place { + from + } else { + return None; + }; + patch::route_admits(state, authority, record.access(), next) + .then(|| (*edge_id, next, u64::from(record.cost().0))) + }) + .collect(); + for (_, next, step) in outbound { + let total = cost + step; + if total <= ceiling && best.get(&next).is_none_or(|known| total < *known) { + best.insert(next, total); + } + } + } +} + +/// Stage 4. Every slot is checked, not just the ones the selected band names: +/// the proposer cannot see the band, so it commits to a complete attempt, and +/// checking every slot makes the ceiling total. +fn check_proposals( + entry: &Affordance, + invocation: &DecisionInvocation, + rejections: &mut Vec, +) { + let mut seen: BTreeSet = BTreeSet::new(); + for proposed in &invocation.proposed { + if !seen.insert(proposed.slot) { + rejections.push(ActionMismatch::DuplicateSlotProposal { + slot: proposed.slot, + }); + continue; + } + let Some(slot) = entry.effect_slots.get(proposed.slot) else { + rejections.push(ActionMismatch::UnknownSlot { + slot: proposed.slot, + }); + continue; + }; + match (slot.bounds, proposed.magnitude) { + (Bounds::None, Magnitude::None) => {} + (Bounds::Quantity(ceiling), Magnitude::Quantity(value)) => { + if value.0 == 0 { + rejections.push(ActionMismatch::ZeroMagnitude { + slot: proposed.slot, + }); + } else if value.0 > ceiling.0 { + rejections.push(ActionMismatch::MagnitudeOverCeiling { + slot: proposed.slot, + }); + } + } + (Bounds::Cost(ceiling), Magnitude::Cost(value)) => { + if value.0 == 0 { + rejections.push(ActionMismatch::ZeroMagnitude { + slot: proposed.slot, + }); + } else if value.0 > ceiling.0 { + rejections.push(ActionMismatch::MagnitudeOverCeiling { + slot: proposed.slot, + }); + } + } + _ => rejections.push(ActionMismatch::MagnitudeShapeMismatch { + slot: proposed.slot, + }), + } + } + for slot in 0..entry.effect_slots.len() { + if !seen.contains(&slot) { + rejections.push(ActionMismatch::SlotNotProposed { slot }); + } + } + // `Statement` is serde-transparent, so a value that arrived through + // deserialization rather than through the constructor is re-checked here + // rather than trusted. + match (&invocation.speech, entry.carries_speech) { + // A speech-carrying entry addresses someone; a silent turn that only + // displays still addresses the room, so it is not `SpeechRequired`. + (None, true) if invocation.display.is_none() => { + rejections.push(ActionMismatch::SpeechRequired); + } + (Some(_), false) => rejections.push(ActionMismatch::SpeechNotCarried), + (Some(speech), true) if !patch::is_canonical_text(speech.as_str()) => { + rejections.push(ActionMismatch::EmptySpeech); + } + _ => {} + } + if invocation + .display + .as_ref() + .is_some_and(|display| !patch::is_canonical_text(display.as_str())) + { + rejections.push(ActionMismatch::EmptyDisplay); + } +} + +/// The only entropy in the kernel: one digest, one modulo, one cumulative walk. +/// Modulo rather than rejection sampling — the bias is bounded by +/// `total_weight / 2^64`, and a rejection loop would need its counter in the +/// preimage, which is a second entropy shape for a rounding error nobody can +/// measure. +fn select_band( + state: &WorldState, + command_id: CommandId, + affordance: AffordanceId, + entry: &Affordance, +) -> Result { + let draw = digest(&BandPreimage { + world_id: state.world_id, + revision: state.revision, + command_id, + affordance, + band_count: entry.outcome_bands.len(), + })?; + let head = draw + .strip_prefix("sha256:") + .and_then(|hex| hex.get(..16)) + .and_then(|head| u64::from_str_radix(head, 16).ok()) + .ok_or_else(|| KernelError::Invariant("band draw digest is not hex".into()))?; + let total: u128 = entry + .outcome_bands + .iter() + .map(|band| u128::from(band.weight)) + .sum(); + if total == 0 { + return Err(KernelError::Invariant( + "affordance has no outcome band".into(), + )); + } + let mut position = u128::from(head) % total; + for (index, band) in entry.outcome_bands.iter().enumerate() { + let weight = u128::from(band.weight); + if position < weight { + return Ok(index); + } + position -= weight; + } + Err(KernelError::Invariant( + "band weights did not cover the draw".into(), + )) +} + +/// Stage 7. One arm per `ComponentOpKind`, every referent read from the slot's +/// roles resolved through the bindings, every magnitude from the proposal for +/// that slot. An empty band lowers to nothing. +fn lower( + entry: &Affordance, + band: usize, + actor: SubjectId, + now: FictionalMinutes, + invocation: &DecisionInvocation, + bindings: &BTreeMap, +) -> Result, KernelError> { + let malformed = || KernelError::Invariant("admitted affordance slot is malformed".into()); + let band = entry + .outcome_bands + .get(band) + .ok_or_else(|| KernelError::Invariant("selected band does not exist".into()))?; + let mut operations = Vec::new(); + for slot_index in &band.effects { + let slot = entry.effect_slots.get(*slot_index).ok_or_else(malformed)?; + let magnitude = invocation + .proposed + .iter() + .find(|proposed| proposed.slot == *slot_index) + .map(|proposed| proposed.magnitude) + .ok_or_else(malformed)?; + let target = |position: usize| -> Result { + slot.roles + .get(position) + .and_then(|role| bindings.get(role)) + .copied() + .ok_or_else(malformed) + }; + let subject = |position: usize| -> Result, KernelError> { + match target(position)? { + Target::Subject(subject_id) => Ok(patch::Ref::Existing(subject_id)), + _ => Err(malformed()), + } + }; + let entity = |position: usize| -> Result, KernelError> { + match target(position)? { + Target::Entity(entity_id) => Ok(patch::Ref::Existing(entity_id)), + _ => Err(malformed()), + } + }; + let edge = |position: usize| -> Result, KernelError> { + match target(position)? { + Target::Edge(edge_id) => Ok(patch::Ref::Existing(edge_id)), + _ => Err(malformed()), + } + }; + let quantity = || -> Result { + match magnitude { + Magnitude::Quantity(value) => Ok(value), + _ => Err(malformed()), + } + }; + let dependency = |position: usize| -> Result { + Ok(match target(position)? { + Target::Subject(subject_id) => { + patch::DependencyRef::Subject(patch::Ref::Existing(subject_id)) + } + Target::Entity(entity_id) => { + patch::DependencyRef::Resource(patch::Ref::Existing(entity_id)) + } + Target::Edge(edge_id) => patch::DependencyRef::Route(patch::Ref::Existing(edge_id)), + }) + }; + let grant_over = |position: usize| -> Result { + Ok(match target(position)? { + Target::Subject(subject_id) => { + patch::AuthorityTargetRef::Subject(patch::Ref::Existing(subject_id)) + } + Target::Entity(entity_id) => { + patch::AuthorityTargetRef::PlaceSubtree(patch::Ref::Existing(entity_id)) + } + Target::Edge(_) => return Err(malformed()), + }) + }; + operations.push(match &slot.op_kind { + // `due` is computed here, so a proposer cannot set one, and the + // pressure source is the acting subject, so it cannot be forged. + ComponentOpKind::CreateCommitment { + kind, + horizon, + period, + } => patch::ComponentOp::CreateCommitment { + subject: subject(0)?, + counterparty: Some(subject(1)?), + kind: *kind, + due: now.checked_add(*horizon).ok_or_else(malformed)?, + period: *period, + checks: Vec::new(), + // The world named the action; that name is what was promised. + // A proposer cannot supply the text, so it cannot promise more + // than the affordance carries. + statement: patch::Statement::new(format!("a promise made through {}", entry.kind.0)) + .ok_or_else(malformed)?, + }, + ComponentOpKind::AdvancePressure { by } => patch::ComponentOp::AdvancePressure { + source: patch::PressureSourceRef::Subject(patch::Ref::Existing(actor)), + target: subject(0)?, + by: *by, + }, + ComponentOpKind::ReducePressure { by } => patch::ComponentOp::ReducePressure { + source: patch::PressureSourceRef::Subject(patch::Ref::Existing(actor)), + target: subject(0)?, + by: *by, + }, + ComponentOpKind::ResolvePressure => patch::ComponentOp::ResolvePressure { + source: patch::PressureSourceRef::Subject(patch::Ref::Existing(actor)), + target: subject(0)?, + }, + ComponentOpKind::Relocate => patch::ComponentOp::Relocate { + subject: subject(0)?, + via: edge(1)?, + }, + ComponentOpKind::OpenRoute => patch::ComponentOp::OpenRoute { route: edge(0)? }, + ComponentOpKind::CloseRoute => patch::ComponentOp::CloseRoute { route: edge(0)? }, + ComponentOpKind::AlterCost => patch::ComponentOp::AlterCost { + route: edge(0)?, + cost: match magnitude { + Magnitude::Cost(value) => value, + _ => return Err(malformed()), + }, + }, + ComponentOpKind::Transfer => patch::ComponentOp::Transfer { + from: subject(0)?, + to: subject(1)?, + resource: entity(2)?, + qty: quantity()?, + }, + ComponentOpKind::Transform => patch::ComponentOp::Transform { + holder: subject(0)?, + from_resource: entity(1)?, + into_resource: entity(2)?, + qty: quantity()?, + }, + ComponentOpKind::Consume => patch::ComponentOp::Consume { + holder: subject(0)?, + resource: entity(1)?, + qty: quantity()?, + }, + ComponentOpKind::Bind => patch::ComponentOp::Bind { + subject: subject(0)?, + target: dependency(1)?, + }, + ComponentOpKind::Release => patch::ComponentOp::Release { + subject: subject(0)?, + target: dependency(1)?, + }, + ComponentOpKind::GrantAuthority { kind } => patch::ComponentOp::GrantAuthority { + holder: subject(0)?, + grant: patch::AuthorityGrantRef { + kind: kind.clone(), + over: grant_over(1)?, + }, + }, + ComponentOpKind::RevokeAuthority { kind } => patch::ComponentOp::RevokeAuthority { + holder: subject(0)?, + grant: patch::AuthorityGrantRef { + kind: kind.clone(), + over: grant_over(1)?, + }, + }, + ComponentOpKind::InstallIncumbent { office } => patch::ComponentOp::InstallIncumbent { + institution: subject(0)?, + office: office.clone(), + incumbent: subject(1)?, + }, + ComponentOpKind::VacateOffice { office } => patch::ComponentOp::VacateOffice { + institution: subject(0)?, + office: office.clone(), + }, + ComponentOpKind::AcquireKnowledge { confidence } => { + patch::ComponentOp::AcquireKnowledge { + subject: subject(0)?, + fact: entity(1)?, + source: patch::AuthoredSource::Witnessed, + confidence: *confidence, + } + } + ComponentOpKind::Witness { confidence } => patch::ComponentOp::Witness { + fact: entity(0)?, + place: entity(1)?, + confidence: *confidence, + }, + ComponentOpKind::Forget => patch::ComponentOp::Forget { + subject: subject(0)?, + fact: entity(1)?, + }, + }); + } + Ok(operations) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::custody_tests::custody_kernel; + use crate::patch::{ + AffordanceDeclaration, ComponentOp, DraftHandle, OutcomeBand, Ref as PatchRef, ResolvedOp, + RoleSpec, + }; + use crate::tests::{ + ADMIT_KIND, COMMAND_KIND, Civic, LEVY_KIND, OPENING_BALANCE, SEIZURE_GRIEVANCE, Topology, + WARDEN_OFFICE, activate, affordance_named, auth_principal, authority_kind, civic_world, + command, custody_world, grant_to, grievance, office, operations, opportunity_for, + over_place, over_subject, human_principal, reject_owner, submit_owner, + }; + use crate::{ + AffordanceKindName, AuthenticatedCaller, AuthoredSource, CallerId, CommandBody, Confidence, + Declaration, EffectSlot, EntityKind, ProposedEffect, RoleBinding, Statement, SubmitReceipt, + WorldEffect, WorldKernel, WorldPatch, WorldSnapshot, apply_effect, + }; + use std::collections::BTreeSet; + + struct Bench { + kernel: WorldKernel, + active: WorldSnapshot, + carry: AffordanceId, + clerk: SubjectId, + keeper: SubjectId, + tithe: EntityId, + ingot: EntityId, + yard: EntityId, + gate: EntityId, + shutter: EdgeId, + } + + fn bench(directory: &std::path::Path, title: &str) -> Bench { + let mut kernel = custody_kernel(directory, title); + let (topology, custody, active) = custody_world(&mut kernel); + let carry = affordance_named(&active, "carry"); + Bench { + kernel, + active, + carry, + clerk: custody.holder, + keeper: custody.counterparty, + tithe: custody.tithe, + ingot: custody.ingot, + yard: topology.yard, + gate: topology.gate, + shutter: topology.shutter, + } + } + + /// `exercise` only accepts a grant the kernel resolved, so a test walks the + /// same gate `reduce` does rather than reaching into the catalog. + fn draw_once( + state: &WorldState, + command_id: CommandId, + opportunity: &DecisionOpportunity, + invocation: &DecisionInvocation, + ) -> Result { + let granted = crate::require_granted(state, opportunity, invocation.affordance)?; + exercise(state, command_id, opportunity, &granted, invocation) + } + + fn binding(role: &str, target: Target) -> RoleBinding { + RoleBinding { + role: Role(role.into()), + target, + } + } + + impl Bench { + /// A Carry the clerk proposes. The actor is never a role, so a Carry + /// that moves the actor's own goods binds `from` to its own id. + fn carry_of(&self, qty: u64, place: EntityId, resource: EntityId) -> DecisionInvocation { + DecisionInvocation { + affordance: self.carry, + bindings: vec![ + binding("from", Target::Subject(self.clerk)), + binding("recipient", Target::Subject(self.keeper)), + binding("place", Target::Entity(place)), + binding("resource", Target::Entity(resource)), + ], + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::Quantity(Quantity(qty)), + }], + speech: None, + display: None, + } + } + + fn carry(&self, qty: u64, place: EntityId) -> DecisionInvocation { + self.carry_of(qty, place, self.tithe) + } + + fn clerk_opportunity(&self) -> DecisionOpportunity { + opportunity_for(&self.active, self.clerk) + } + + fn try_exercise( + &self, + invocation: &DecisionInvocation, + ) -> Result { + let opportunity = self.clerk_opportunity(); + draw_once( + &self.kernel.state, + CommandId::issue(), + &opportunity, + invocation, + ) + } + + fn rejections(&self, invocation: &DecisionInvocation) -> Vec { + match self.try_exercise(invocation) { + Err(KernelError::ActionRejected(rejected)) => rejected, + other => panic!("expected an action rejection, got {other:?}"), + } + } + + fn commit(&mut self, invocation: DecisionInvocation) -> SubmitReceipt { + let opportunity = self.clerk_opportunity(); + let caller = CallerId::Controller(opportunity.controller_id); + self.kernel + .submit( + command( + &self.active, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + opportunity, + invocation, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .expect("the invocation commits") + } + + fn held(&self, holder: SubjectId) -> u64 { + self.kernel + .state + .holdings + .get(&holder) + .and_then(|held| held.get(&self.tithe)) + .map_or(0, |quantity| quantity.0) + } + + /// The same Carry attempt against a sibling entry: one dial moved, one + /// name. The catalog is Draft-only, so a variant is declared rather + /// than patched into committed state. + fn variant(&self, invocation: &DecisionInvocation, kind: &str) -> DecisionInvocation { + DecisionInvocation { + affordance: affordance_named(&self.active, kind), + ..invocation.clone() + } + } + + fn refresh(&mut self) { + self.active = self.kernel.snapshot().unwrap(); + } + } + + #[test] + fn a_missing_present_precondition_names_itself() { + let directory = tempfile::tempdir().unwrap(); + let bench = bench(directory.path(), "Present"); + let before = bench.kernel.state.clone(); + + // The clerk stands in the yard, so a Carry bound to the gate fails the + // first precondition and nothing else. + assert_eq!( + bench.rejections(&bench.carry(1, bench.gate)), + vec![ActionMismatch::ActorNotPresent { precondition: 0 }] + ); + assert_eq!(bench.kernel.state.revision, before.revision); + assert_eq!(bench.kernel.state.holdings, before.holdings); + assert_eq!(bench.kernel.state.events, before.events); + } + + #[test] + fn spending_more_than_held_fails_the_holds_precondition() { + let directory = tempfile::tempdir().unwrap(); + let bench = bench(directory.path(), "Holds"); + let greedy = bench.variant(&bench.carry(1, bench.yard), "carry_greedy"); + assert_eq!( + bench.rejections(&greedy), + vec![ActionMismatch::InsufficientHolding { precondition: 1 }] + ); + + // Absence is zero, so a resource the clerk holds none of gives the same + // name at the boundary rather than a second one. + let ingot = bench.variant(&bench.carry_of(1, bench.yard, bench.ingot), "carry_holds"); + assert_eq!( + bench.rejections(&ingot), + vec![ActionMismatch::InsufficientHolding { precondition: 0 }] + ); + } + + #[test] + fn a_reachable_precondition_reads_only_open_public_routes() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = bench(directory.path(), "Reachable"); + // Yard to gate over open public routes is the ramp (12) plus the span + // (7): the shutter is closed and the toll stair is restricted. A budget + // of NEAR_REACH covers only the shutter, FAR_REACH covers the two-hop + // path. + let attempt = bench.carry(1, bench.gate); + let near = bench.variant(&attempt, "carry_near"); + let far = bench.variant(&attempt, "carry_far"); + assert_eq!( + bench.rejections(&near), + vec![ActionMismatch::TargetUnreachable { precondition: 0 }] + ); + assert!(bench.try_exercise(&far).is_ok()); + + // Opening the one-hop shutter shortens the path, and closing it again + // restores the two-hop cost: the check reads the live graph rather than + // anything the proposal was bound against. + let before = bench.kernel.snapshot().unwrap(); + submit_owner( + &mut bench.kernel, + &before, + operations(vec![ComponentOp::OpenRoute { + route: PatchRef::Existing(bench.shutter), + }]), + ); + bench.refresh(); + assert!(bench.try_exercise(&near).is_ok()); + + let before = bench.kernel.snapshot().unwrap(); + submit_owner( + &mut bench.kernel, + &before, + operations(vec![ComponentOp::CloseRoute { + route: PatchRef::Existing(bench.shutter), + }]), + ); + bench.refresh(); + assert_eq!( + bench.rejections(&near), + vec![ActionMismatch::TargetUnreachable { precondition: 0 }] + ); + } + + #[test] + fn an_unbound_or_miskinded_role_is_rejected_with_the_complete_set() { + let directory = tempfile::tempdir().unwrap(); + let bench = bench(directory.path(), "Roles"); + let mut invocation = bench.carry(1, bench.yard); + // Drop `recipient`, add an undeclared role, and bind `resource` to a + // place: one rejection carrying all three, sorted. + invocation.bindings = vec![ + binding("from", Target::Subject(bench.clerk)), + binding("place", Target::Entity(bench.yard)), + binding("resource", Target::Entity(bench.yard)), + binding("porter", Target::Subject(bench.keeper)), + ]; + let mut expected = vec![ + ActionMismatch::UnboundRole { + role: Role("recipient".into()), + }, + ActionMismatch::UnknownRole { + role: Role("porter".into()), + }, + ActionMismatch::TargetKindMismatch { + role: Role("resource".into()), + expected: RefKind::Entity(EntityKind::Resource), + actual: RefKind::Entity(EntityKind::Place), + }, + ]; + expected.sort(); + assert_eq!(bench.rejections(&invocation), expected); + } + + #[test] + fn a_duplicated_or_unknown_binding_target_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let bench = bench(directory.path(), "Bindings"); + let mut twice = bench.carry(1, bench.yard); + twice + .bindings + .push(binding("resource", Target::Entity(bench.tithe))); + assert!( + bench + .rejections(&twice) + .contains(&ActionMismatch::DuplicateRoleBinding { + role: Role("resource".into()) + }) + ); + + let mut unknown = bench.carry(1, bench.yard); + unknown.bindings[3] = binding("resource", Target::Entity(EntityId::issue())); + assert!( + bench + .rejections(&unknown) + .contains(&ActionMismatch::UnknownTarget { + role: Role("resource".into()) + }) + ); + } + + #[test] + fn a_magnitude_over_its_slot_ceiling_is_rejected_and_within_it_commits() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = bench(directory.path(), "Ceiling"); + assert_eq!( + bench.rejections(&bench.carry(4, bench.yard)), + vec![ActionMismatch::MagnitudeOverCeiling { slot: 0 }] + ); + + let clerk_before = bench.held(bench.clerk); + let keeper_before = bench.held(bench.keeper); + let receipt = bench.commit(bench.carry(3, bench.yard)); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert_eq!(bench.held(bench.clerk), clerk_before - 3); + assert_eq!(bench.held(bench.keeper), keeper_before + 3); + assert_eq!( + bench.held(bench.clerk) + bench.held(bench.keeper), + clerk_before + keeper_before, + "the conserved total is unchanged" + ); + } + + #[test] + fn a_magnitude_of_the_wrong_shape_or_zero_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let bench = bench(directory.path(), "Shape"); + for magnitude in [Magnitude::Cost(Cost(2)), Magnitude::None] { + let mut invocation = bench.carry(1, bench.yard); + invocation.proposed[0].magnitude = magnitude; + assert_eq!( + bench.rejections(&invocation), + vec![ActionMismatch::MagnitudeShapeMismatch { slot: 0 }] + ); + } + assert_eq!( + bench.rejections(&bench.carry(0, bench.yard)), + vec![ActionMismatch::ZeroMagnitude { slot: 0 }] + ); + } + + #[test] + fn every_slot_must_be_proposed_exactly_once() { + let directory = tempfile::tempdir().unwrap(); + let bench = bench(directory.path(), "Slots"); + let mut missing = bench.carry(1, bench.yard); + missing.proposed.clear(); + assert_eq!( + bench.rejections(&missing), + vec![ActionMismatch::SlotNotProposed { slot: 0 }] + ); + + let mut twice = bench.carry(1, bench.yard); + twice.proposed.push(twice.proposed[0]); + assert_eq!( + bench.rejections(&twice), + vec![ActionMismatch::DuplicateSlotProposal { slot: 0 }] + ); + + let mut unknown = bench.carry(1, bench.yard); + unknown.proposed.push(ProposedEffect { + slot: 7, + magnitude: Magnitude::None, + }); + assert_eq!( + bench.rejections(&unknown), + vec![ActionMismatch::UnknownSlot { slot: 7 }] + ); + } + + #[test] + fn speech_is_required_exactly_when_the_entry_carries_it() { + let directory = tempfile::tempdir().unwrap(); + let bench = bench(directory.path(), "Speech"); + let mut spoken_carry = bench.carry(1, bench.yard); + spoken_carry.speech = Some(Statement::new("Take it.").unwrap()); + assert_eq!( + bench.rejections(&spoken_carry), + vec![ActionMismatch::SpeechNotCarried] + ); + + let speak = affordance_named(&bench.active, "speak"); + let mut silent_speak = DecisionInvocation { + affordance: speak, + bindings: Vec::new(), + proposed: Vec::new(), + speech: None, + display: None, + }; + assert_eq!( + bench.rejections(&silent_speak), + vec![ActionMismatch::SpeechRequired] + ); + + // `Statement` is serde-transparent, so a value that arrived without the + // constructor is re-checked here rather than trusted. + silent_speak.speech = Some(serde_json::from_str::("\" \"").unwrap()); + assert_eq!( + bench.rejections(&silent_speak), + vec![ActionMismatch::EmptySpeech] + ); + } + + #[test] + fn the_same_command_id_always_selects_the_same_band() { + let directory = tempfile::tempdir().unwrap(); + let bench = bench(directory.path(), "Bands"); + // Three equally weighted bands, so the draw alone decides. + let opportunity = bench.clerk_opportunity(); + let invocation = bench.variant(&bench.carry(1, bench.yard), "carry_chance"); + let draw = |command_id: CommandId, invocation: &DecisionInvocation| { + draw_once(&bench.kernel.state, command_id, &opportunity, invocation) + .expect("the invocation is admissible") + .band + }; + + let command_id = CommandId::issue(); + let fixed = draw(command_id, &invocation); + for _ in 0..100 { + assert_eq!(draw(command_id, &invocation), fixed); + } + + // No caller-supplied value influences the draw: not a binding order, + // not a magnitude. + let mut reordered = invocation.clone(); + reordered.bindings.reverse(); + assert_eq!(draw(command_id, &reordered), fixed); + let mut heavier = invocation.clone(); + heavier.proposed[0].magnitude = Magnitude::Quantity(Quantity(3)); + assert_eq!(draw(command_id, &heavier), fixed); + + // The command id is the only varying term at one revision. + let mut seen = BTreeSet::new(); + for _ in 0..64 { + seen.insert(draw(CommandId::issue(), &invocation)); + } + assert!( + seen.len() > 1, + "varying only the command id must reach more than one band" + ); + } + + #[test] + fn a_zero_effect_band_commits_nothing_but_the_event() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = bench(directory.path(), "EmptyBand"); + let idle = bench.variant(&bench.carry(3, bench.yard), "carry_idle"); + + let holdings = bench.kernel.state.holdings.clone(); + let positions = bench.kernel.state.positions.clone(); + let edges = bench.kernel.state.edges.clone(); + let revision = bench.kernel.state.revision; + + let event = bench + .try_exercise(&idle) + .expect("an empty band is admissible"); + assert_eq!(event.band, 0); + assert!(event.effects.is_empty()); + + let receipt = bench.commit(idle); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert_eq!(bench.kernel.state.holdings, holdings); + assert_eq!(bench.kernel.state.positions, positions); + assert_eq!(bench.kernel.state.edges, edges); + assert_eq!(bench.kernel.state.events.len(), 1); + assert_eq!(bench.kernel.state.revision, revision + 1); + } + + #[test] + fn a_committed_event_carries_the_exact_lowered_operations() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = bench(directory.path(), "Lowering"); + let receipt = bench.commit(bench.carry(2, bench.yard)); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + let event = bench + .kernel + .state + .events + .last() + .expect("the committed event"); + assert_eq!( + event.effects, + vec![ResolvedOp::Transfer { + from: bench.clerk, + to: bench.keeper, + resource: bench.tithe, + qty: Quantity(2), + }] + ); + } + + /// Soul: contract 10's discriminating case. `a_zero_effect_band_commits_ + /// nothing_but_the_event` proves an empty band commits nothing, and + /// `a_committed_event_carries_the_exact_lowered_operations` proves a + /// one-slot entry lowers what it declares — neither separates a slot the + /// proposer offered from a slot the draw admitted. This entry declares two + /// slots on disjoint bands and proposes both within their ceilings: only + /// the drawn band's slot may appear in `event.effects`, and the other slot + /// must move no partition. Both bands are exercised, so neither branch + /// passes by never being taken. + #[test] + fn soul_only_the_selected_bands_effects_are_committed() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = bench(directory.path(), "SelectedBand"); + let split_id = affordance_named(&bench.active, "carry_split"); + let split = DecisionInvocation { + affordance: split_id, + bindings: vec![ + binding("from", Target::Subject(bench.clerk)), + binding("recipient", Target::Subject(bench.keeper)), + binding("place", Target::Entity(bench.yard)), + binding("resource", Target::Entity(bench.tithe)), + ], + proposed: vec![ + ProposedEffect { + slot: 0, + magnitude: Magnitude::Quantity(Quantity(2)), + }, + ProposedEffect { + slot: 1, + magnitude: Magnitude::Quantity(Quantity(1)), + }, + ], + speech: None, + display: None, + }; + let mut seen: BTreeSet = BTreeSet::new(); + + for wanted in [0usize, 1] { + // The draw is a pure function of the pre-commit revision and the + // command id, so the command id that reaches a band is findable + // before the envelope is built rather than hunted by retrying. + let opportunity = bench.clerk_opportunity(); + let command_id = (0..256) + .map(|_| CommandId::issue()) + .find(|candidate| { + draw_once(&bench.kernel.state, *candidate, &opportunity, &split) + .expect("the invocation is admissible") + .band + == wanted + }) + .expect("a two-band entry reaches both bands over 256 command ids"); + + let before_clerk = bench.held(bench.clerk); + let before_keeper = bench.held(bench.keeper); + let caller = CallerId::Controller(opportunity.controller_id); + let receipt = bench + .kernel + .submit( + command( + &bench.active, + command_id, + caller.clone(), + CommandBody::ExerciseDecision { + opportunity, + invocation: split.clone(), + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .expect("the invocation commits"); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + bench.refresh(); + let event = bench + .kernel + .state + .events + .last() + .expect("the committed event") + .clone(); + assert_eq!(event.band, wanted); + seen.insert(event.band); + match event.band { + 0 => { + assert_eq!( + event.effects, + vec![ResolvedOp::Transfer { + from: bench.clerk, + to: bench.keeper, + resource: bench.tithe, + qty: Quantity(2), + }] + ); + assert_eq!(bench.held(bench.clerk), before_clerk - 2); + assert_eq!(bench.held(bench.keeper), before_keeper + 2); + } + 1 => { + assert_eq!( + event.effects, + vec![ResolvedOp::Consume { + holder: bench.clerk, + resource: bench.tithe, + qty: Quantity(1), + }] + ); + assert_eq!(bench.held(bench.clerk), before_clerk - 1); + assert_eq!(bench.held(bench.keeper), before_keeper); + } + other => panic!("the entry declares two bands, drew {other}"), + } + } + + assert_eq!( + seen.len(), + 2, + "both declared bands must be reachable across command ids" + ); + } + + /// Soul: `RoleSpec` persists inside the catalog, so `RefKind` had to become + /// serializable this pass. An internally tagged newtype over an `Option` + /// does not serialize; this one is adjacently tagged, and a stored + /// `Subject(None)` role is what would fault on first write if that were + /// wrong. The fixture catalog carries four such roles. + #[test] + fn soul_a_stored_role_spec_over_an_optional_subject_kind_round_trips() { + let directory = tempfile::tempdir().unwrap(); + let bench = bench(directory.path(), "OptionalSubjectKind"); + let entry = bench + .kernel + .state + .affordance_catalog + .get(&bench.carry) + .expect("the fixture entry"); + assert!( + entry + .roles + .iter() + .any(|spec| spec.kind == RefKind::Subject(None)) + ); + + // The state row encoder and the digest owner are the same `to_vec_named` + // path the store writes through. + let encoded = rmp_serde::to_vec_named(&bench.kernel.state).expect("the state encodes"); + let decoded: WorldState = rmp_serde::from_slice(&encoded).expect("the state decodes"); + assert_eq!( + decoded.affordance_catalog, + bench.kernel.state.affordance_catalog + ); + assert!(digest(&bench.kernel.state).is_ok()); + } + + #[test] + fn a_forged_band_or_forged_effect_does_not_apply() { + let directory = tempfile::tempdir().unwrap(); + let bench = bench(directory.path(), "ForgedAction"); + let opportunity = bench.clerk_opportunity(); + let command_id = CommandId::issue(); + let invocation = bench.carry(2, bench.yard); + let honest = draw_once(&bench.kernel.state, command_id, &opportunity, &invocation).unwrap(); + let caller = CallerId::Controller(opportunity.controller_id); + + for forged in [ + DecisionEvent { + band: 3, + ..honest.clone() + }, + DecisionEvent { + effects: vec![ResolvedOp::Transfer { + from: bench.clerk, + to: bench.keeper, + resource: bench.tithe, + qty: Quantity(OPENING_BALANCE), + }], + ..honest.clone() + }, + ] { + let mut candidate = bench.kernel.state.clone(); + let error = apply_effect( + &mut candidate, + command_id, + &caller, + &WorldEffect::DecisionExercised { + opportunity: opportunity.clone(), + invocation: invocation.clone(), + event: forged, + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_))); + assert_eq!(candidate, bench.kernel.state); + } + + // The honest event still applies through the same arm. + let mut candidate = bench.kernel.state.clone(); + apply_effect( + &mut candidate, + command_id, + &caller, + &WorldEffect::DecisionExercised { + opportunity, + invocation: invocation.clone(), + event: honest, + }, + ) + .unwrap(); + assert_ne!(candidate.holdings, bench.kernel.state.holdings); + } + + #[test] + fn the_kernel_speak_entry_commits_its_utterance_and_no_operation() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "SpeakEntry"); + let _topology = activate(&mut kernel); + let active = kernel.snapshot().unwrap(); + let speak = affordance_named(&active, "speak"); + let human = active + .subjects + .iter() + .find(|subject| subject.human_controller.is_some()) + .expect("the human subject") + .id; + let holdings = kernel.state.holdings.clone(); + let receipt = kernel + .submit( + command( + &active, + CommandId::new(), + CallerId::Principal(human_principal()), + CommandBody::ExerciseDecision { + opportunity: opportunity_for(&active, human), + invocation: DecisionInvocation { + affordance: speak, + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Statement::new("I open the door.").unwrap()), + display: None, + }, + }, + ), + &auth_principal(human_principal()), + ) + .expect("the Speak entry commits"); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + let event = kernel.state.events.last().unwrap(); + assert_eq!(event.band, 0); + // The two the speech lowering prepends, and nothing from a slot. + assert_eq!(event.effects.len(), 2); + assert_eq!( + crate::tests::spoken(&kernel.state, event), + Some("I open the door.") + ); + assert_eq!(kernel.state.holdings, holdings); + } + + /// The civic bench: one world where an institution holds jurisdiction over + /// a hall, a person holds the same jurisdiction only through an office, and + /// two more people stand inside and outside that ground. + struct Civics { + kernel: WorldKernel, + active: WorldSnapshot, + topology: Topology, + civic: Civic, + } + + fn civics(directory: &std::path::Path, title: &str) -> Civics { + let mut kernel = custody_kernel(directory, title); + let (topology, civic, active) = civic_world(&mut kernel); + Civics { + kernel, + active, + topology, + civic, + } + } + + impl Civics { + fn refresh(&mut self) { + self.active = self.kernel.snapshot().unwrap(); + } + + fn call( + &self, + kind: &str, + bindings: Vec, + proposed: Vec, + speech: Option, + ) -> DecisionInvocation { + DecisionInvocation { + affordance: affordance_named(&self.active, kind), + bindings, + proposed, + speech, + display: None, + } + } + + /// A levy of `qty` from `payer`, always paid to the actor: the payee is + /// the reserved role, so it is not a binding the caller supplies. + fn levy(&self, payer: SubjectId, qty: u64) -> DecisionInvocation { + self.call( + "levy", + vec![ + binding("payer", Target::Subject(payer)), + binding("resource", Target::Entity(self.civic.grain)), + ], + vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::Quantity(Quantity(qty)), + }], + None, + ) + } + + fn delegate(&self, deputy: SubjectId, ground: EntityId) -> DecisionInvocation { + self.call( + "delegate", + vec![ + binding("deputy", Target::Subject(deputy)), + binding("ground", Target::Entity(ground)), + ], + vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + None, + ) + } + + /// Commands a subordinate to traverse a route: the fixture's one + /// `Relocate`-lowering affordance, gated by `command` authority over + /// the subordinate rather than by the subordinate's own consent. + fn deploy(&self, subordinate: SubjectId, via: EdgeId) -> DecisionInvocation { + self.call( + "deploy", + vec![ + binding("subordinate", Target::Subject(subordinate)), + binding("via", Target::Edge(via)), + ], + vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + None, + ) + } + + /// Strips `holder`'s `levy` grant over `ground`: the fixture's one + /// `RevokeAuthority`-lowering affordance, carrying no precondition of + /// its own so a rejection can only be the action lane's revocation + /// envelope. + fn revoke(&self, holder: SubjectId, ground: EntityId) -> DecisionInvocation { + self.call( + "revoke", + vec![ + binding("holder", Target::Subject(holder)), + binding("ground", Target::Entity(ground)), + ], + vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + None, + ) + } + + fn try_as( + &self, + actor: SubjectId, + invocation: &DecisionInvocation, + ) -> Result { + draw_once( + &self.kernel.state, + CommandId::issue(), + &opportunity_for(&self.active, actor), + invocation, + ) + } + + fn rejected_as( + &self, + actor: SubjectId, + invocation: &DecisionInvocation, + ) -> Vec { + match self.try_as(actor, invocation) { + Err(KernelError::ActionRejected(rejected)) => rejected, + other => panic!("expected an action rejection, got {other:?}"), + } + } + + fn commit_as(&mut self, actor: SubjectId, invocation: DecisionInvocation) -> SubmitReceipt { + let opportunity = opportunity_for(&self.active, actor); + let caller = CallerId::Controller(opportunity.controller_id); + let receipt = self + .kernel + .submit( + command( + &self.active, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + opportunity, + invocation, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .expect("the invocation commits"); + self.refresh(); + receipt + } + + fn admit(&mut self, ops: Vec) { + let before = self.kernel.snapshot().unwrap(); + let receipt = submit_owner(&mut self.kernel, &before, operations(ops)); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + self.refresh(); + } + + fn refuse(&mut self, ops: Vec) -> Vec { + let before = self.kernel.snapshot().unwrap(); + reject_owner(&mut self.kernel, &before, operations(ops)) + } + } + + /// Contract 7's third rejection: commanding outside authority, with the + /// exact failed precondition and no allocation. + #[test] + fn an_unauthorized_actor_names_the_failed_precondition() { + let directory = tempfile::tempdir().unwrap(); + let bench = civics(directory.path(), "Unauthorized"); + let before = bench.kernel.state.clone(); + assert_eq!( + bench.rejected_as(bench.civic.farmer, &bench.levy(bench.civic.reeve, 1)), + vec![ActionMismatch::NotAuthorized { precondition: 0 }] + ); + assert_eq!(bench.kernel.state.revision, before.revision); + assert_eq!(bench.kernel.state.holdings, before.holdings); + assert_eq!(bench.kernel.state.events, before.events); + } + + /// A place jurisdiction reaches everything under it and nothing else, and + /// the answer is read live: a target that walks out of the subtree stops + /// being authorized without any digest moving. + #[test] + fn place_jurisdiction_reaches_a_containment_subtree_and_stops_at_its_edge() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = civics(directory.path(), "Subtree"); + let treasury = bench.civic.treasury; + let farmer = bench.civic.farmer; + + // The farmer stands in the chamber, whose container is the hall. + assert!(bench.try_as(treasury, &bench.levy(farmer, 1)).is_ok()); + + // The pedlar stands on the road, outside the hall entirely, and an + // unplaced subject is covered by no place target. + assert_eq!( + bench.rejected_as(treasury, &bench.levy(bench.civic.outsider, 1)), + vec![ActionMismatch::NotAuthorized { precondition: 0 }] + ); + let unplaced = *bench + .kernel + .state + .subjects + .keys() + .find(|subject_id| !bench.kernel.state.positions.contains_key(subject_id)) + .expect("the genesis world declares an unplaced subject"); + assert_eq!( + bench.rejected_as(treasury, &bench.levy(unplaced, 1)), + vec![ActionMismatch::NotAuthorized { precondition: 0 }] + ); + + // Walking the farmer out of the hall flips the same invocation, and a + // grant naming the subject directly authorizes it again. + bench.admit(vec![ + ComponentOp::Relocate { + subject: PatchRef::Existing(farmer), + via: PatchRef::Existing(bench.civic.passage), + }, + ComponentOp::Relocate { + subject: PatchRef::Existing(farmer), + via: PatchRef::Existing(bench.civic.causeway), + }, + ]); + assert_eq!( + bench.rejected_as(treasury, &bench.levy(farmer, 1)), + vec![ActionMismatch::NotAuthorized { precondition: 0 }] + ); + bench.admit(vec![grant_to(treasury, LEVY_KIND, over_subject(farmer))]); + assert!(bench.try_as(treasury, &bench.levy(farmer, 1)).is_ok()); + } + + /// An office lends jurisdiction its holder does not own, vacating takes it + /// back, and a proposal bound before the vacate rebinds rather than + /// rejecting: revocation mid-flight is a `ScopeChanged`. + #[test] + fn office_delegation_grants_and_vacating_revokes() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = civics(directory.path(), "Office"); + let reeve = bench.civic.reeve; + let farmer = bench.civic.farmer; + assert!(bench.kernel.state.authority.get(&reeve).is_none()); + assert!(bench.try_as(reeve, &bench.levy(farmer, 1)).is_ok()); + + // A proposal bound before the vacate rebinds rather than rejecting. + let bound = opportunity_for(&bench.active, reeve); + let caller = CallerId::Controller(bound.controller_id); + let invocation = bench.levy(farmer, 1); + bench.admit(vec![ComponentOp::VacateOffice { + institution: PatchRef::Existing(bench.civic.treasury), + office: office(WARDEN_OFFICE), + }]); + + let holdings = bench.kernel.state.holdings.clone(); + let error = bench + .kernel + .submit( + command( + &bench.active, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + opportunity: bound.clone(), + invocation, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .unwrap_err(); + let KernelError::ScopeChanged { + scope, expected, .. + } = error + else { + panic!("a vacated office is a rebind, not a rejection"); + }; + assert_eq!(scope, bound.scope); + assert_eq!(expected, bound.scope_digest); + assert_eq!(bench.kernel.state.holdings, holdings); + assert_eq!( + bench.rejected_as(reeve, &bench.levy(farmer, 1)), + vec![ActionMismatch::NotAuthorized { precondition: 0 }] + ); + } + + /// The reserved role in both directions: an invocation may not bind it, and + /// a catalog entry may not declare it. + #[test] + fn a_levy_cannot_be_directed_away_from_the_actor() { + let directory = tempfile::tempdir().unwrap(); + let bench = civics(directory.path(), "ActorRole"); + let mut redirected = bench.levy(bench.civic.farmer, 1); + redirected + .bindings + .push(binding("actor", Target::Subject(bench.civic.outsider))); + assert_eq!( + bench.rejected_as(bench.civic.treasury, &redirected), + vec![ActionMismatch::ActorRoleBound] + ); + + // The declaration half is Draft-only, so it runs against a fresh world. + let draft_directory = tempfile::tempdir().unwrap(); + let mut draft = custody_kernel(draft_directory.path(), "ReservedRole"); + let before = draft.snapshot().unwrap(); + let handle = DraftHandle::new("thief"); + let rejected = reject_owner( + &mut draft, + &before, + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![Declaration::Affordance(AffordanceDeclaration { + handle: handle.clone(), + kind: AffordanceKindName("thief".into()), + roles: vec![RoleSpec { + role: Role("actor".into()), + kind: RefKind::Subject(None), + }], + preconditions: vec![Precondition::CanBroadcast { + via: AudienceSpec::Colocated, + }], + effect_slots: Vec::new(), + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + carries_speech: true, + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ); + assert!(rejected.contains(&crate::Mismatch::ReservedRole { handle })); + } + + /// The two rejection lanes stay distinguishable: an over-levy inside its + /// declared ceiling passes every affordance check and dies in the ledger. + #[test] + fn an_over_levy_fails_in_the_ledger_not_in_the_contract() { + let directory = tempfile::tempdir().unwrap(); + let bench = civics(directory.path(), "OverLevy"); + let error = bench + .try_as(bench.civic.treasury, &bench.levy(bench.civic.farmer, 9)) + .unwrap_err(); + let KernelError::PatchRejected(rejected) = error else { + panic!("an over-levy is a ledger rejection"); + }; + assert_eq!( + rejected, + vec![crate::Mismatch::InsufficientCustody { operation: 0 }] + ); + } + + /// A delegated grant may not exceed the granter's own, and the grant it + /// does mint is still subject to disjointness. + #[test] + fn a_delegated_grant_may_not_exceed_the_granter() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = civics(directory.path(), "Monotone"); + let treasury = bench.civic.treasury; + let outsider = bench.civic.outsider; + + // The treasury commands the road but does not levy it, so the + // precondition passes and the delegation alone is refused. + let road = bench.topology.road; + bench.admit(vec![grant_to(treasury, COMMAND_KIND, over_place(road))]); + let outside = bench.delegate(outsider, road); + assert_eq!( + bench.rejected_as(treasury, &outside), + vec![ActionMismatch::DelegationNotMonotone { slot: 0 }] + ); + + // The chamber is inside it, so the same act commits and the deputy can + // then levy there. + let inside = bench.delegate(outsider, bench.civic.chamber); + assert!(matches!( + bench.commit_as(treasury, inside), + SubmitReceipt::Applied(_) + )); + assert!( + bench + .try_as(outsider, &bench.levy(bench.civic.farmer, 1)) + .is_ok() + ); + + // An office lends exactly the kinds it delegates: the warden's `levy` + // does not make its holder a commander. + let again = bench.delegate(outsider, bench.civic.chamber); + assert_eq!( + bench.rejected_as(bench.civic.reeve, &again), + vec![ActionMismatch::NotAuthorized { precondition: 0 }] + ); + + // The minted grant is ordinary state: repeating it changes nothing, and + // widening it to the hall would overlap what the deputy already holds. + let error = bench.try_as(treasury, &again).unwrap_err(); + let KernelError::PatchRejected(rejected) = error else { + panic!("a duplicate delegation is a patch rejection"); + }; + assert_eq!( + rejected, + vec![crate::Mismatch::NoOperationEffect { operation: 0 }] + ); + let hall = bench.civic.hall; + assert_eq!( + bench.refuse(vec![grant_to(outsider, LEVY_KIND, over_place(hall))]), + vec![crate::Mismatch::OverlappingJurisdiction { operation: 0 }] + ); + } + + /// The revocation envelope is the same predicate as the grant one, read + /// the other way: an actor may strip a `levy` grant only over ground its + /// own authority covers, so a bystander cannot use `revoke` to reach past + /// what it may otherwise touch. + #[test] + fn revoking_a_grant_requires_covering_authority_over_its_ground() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = civics(directory.path(), "RevokeEnvelope"); + let treasury = bench.civic.treasury; + let farmer = bench.civic.farmer; + let hall = bench.civic.hall; + + // The farmer holds no authority at all, so stripping the treasury's + // own `levy` grant over the hall fails the envelope before the patch + // lane ever sees the operation. + assert_eq!( + bench.rejected_as(farmer, &bench.revoke(treasury, hall)), + vec![ActionMismatch::DelegationNotMonotone { slot: 0 }] + ); + + // The treasury's own `levy` grant over the hall covers the hall, so + // the treasury may strip its own grant, and the ledger loses it. + assert!(matches!( + bench.commit_as(treasury, bench.revoke(treasury, hall)), + SubmitReceipt::Applied(_) + )); + assert!( + !bench + .kernel + .state + .authority + .get(&treasury) + .is_some_and(|grants| grants.contains(&crate::AuthorityGrant { + kind: authority_kind(LEVY_KIND), + over: crate::AuthorityTarget::PlaceSubtree(hall), + })), + "the revoked grant is gone from the ledger" + ); + } + + /// The fixture's one `Relocate`-lowering affordance: a commander may move + /// a subordinate standing under its ground, and one standing outside it + /// fails the same `Authorized` precondition every other civic act reads. + #[test] + fn deploy_relocates_a_subordinate_under_command_and_refuses_one_outside_it() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = civics(directory.path(), "Deploy"); + let treasury = bench.civic.treasury; + let farmer = bench.civic.farmer; + let outsider = bench.civic.outsider; + let chamber = bench.civic.chamber; + let hall = bench.civic.hall; + let passage = bench.civic.passage; + + // The pedlar stands on the road, outside the hall the treasury + // commands, so the precondition alone refuses the attempt. + assert_eq!( + bench.rejected_as(treasury, &bench.deploy(outsider, passage)), + vec![ActionMismatch::NotAuthorized { precondition: 0 }] + ); + + // The farmer stands in the chamber, under the treasury's command, and + // the passage carries it into the hall the same way a direct + // `Relocate` would. + assert_eq!( + bench + .kernel + .state + .positions + .get(&farmer) + .map(|position| position.place), + Some(chamber) + ); + assert!(matches!( + bench.commit_as(treasury, bench.deploy(farmer, passage)), + SubmitReceipt::Applied(_) + )); + assert_eq!( + bench + .kernel + .state + .positions + .get(&farmer) + .map(|position| position.place), + Some(hall) + ); + } + + /// `Redress` with a reducer reader: standing is the covering predicate over + /// the forum's target, and closing the forum removes the verb's ground. + #[test] + fn a_petition_requires_standing() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = civics(directory.path(), "Petition"); + let petition = bench.call( + "petition", + Vec::new(), + Vec::new(), + Some(Statement::new("The tithe was taken twice.").unwrap()), + ); + assert_eq!( + bench.rejected_as(bench.civic.outsider, &petition), + vec![ActionMismatch::NoStanding { precondition: 0 }] + ); + + let farmer = bench.civic.farmer; + assert!(matches!( + bench.commit_as(farmer, petition.clone()), + SubmitReceipt::Applied(_) + )); + let event = bench + .kernel + .state + .events + .last() + .expect("the committed event"); + assert_eq!(event.effects.len(), 2); + assert_eq!( + crate::tests::spoken(&bench.kernel.state, event), + Some("The tithe was taken twice.") + ); + + bench.admit(vec![ComponentOp::CloseForum { + grievance: grievance(SEIZURE_GRIEVANCE), + }]); + assert_eq!( + bench.rejected_as(farmer, &petition), + vec![ActionMismatch::NoStanding { precondition: 0 }] + ); + } + + /// One predicate, two callers: the resolver's `Relocate` arm and + /// `Reachable`'s edge admission read the same `Restricted` rule, and a + /// same-patch grant then move resolves through the candidate shadow. + #[test] + fn a_restricted_route_admits_exactly_its_named_authority() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = civics(directory.path(), "Restricted"); + let walker = bench.topology.walker; + let step = ComponentOp::Relocate { + subject: PatchRef::Existing(walker), + via: PatchRef::Existing(bench.civic.postern), + }; + + // Holding nothing, and holding `admit` over the origin only, are both + // refused: the rule asks about the destination. + assert!( + bench + .refuse(vec![step.clone()]) + .contains(&crate::Mismatch::RouteAccessRestricted { operation: 0 }) + ); + let yard = bench.topology.yard; + bench.admit(vec![grant_to(walker, ADMIT_KIND, over_place(yard))]); + assert!( + bench + .refuse(vec![step.clone()]) + .contains(&crate::Mismatch::RouteAccessRestricted { operation: 0 }) + ); + + // Reachable reads the same rule from the other side. + let authority = crate::subject_authority(&bench.kernel.state, walker); + assert!(!reachable( + &bench.kernel.state, + walker, + &authority, + bench.civic.chamber, + Cost(4) + )); + + // A grant covering the destination, minted in the same patch as the + // move, resolves through the candidate authority shadow. + let hall = bench.civic.hall; + let authority = crate::subject_authority(&bench.kernel.state, walker); + assert!(!patch::route_admits( + &bench.kernel.state, + &authority, + bench.kernel.state.edges[&bench.civic.postern].access(), + bench.civic.chamber + )); + bench.admit(vec![grant_to(walker, ADMIT_KIND, over_place(hall)), step]); + assert_eq!( + bench.kernel.state.positions[&walker].place, + bench.civic.chamber + ); + let authority = crate::subject_authority(&bench.kernel.state, walker); + assert!(patch::route_admits( + &bench.kernel.state, + &authority, + bench.kernel.state.edges[&bench.civic.postern].access(), + bench.civic.chamber + )); + } + + /// The remaining institutional affordances, each proving one lowering arm: + /// `sanction` closes shared topology under a legitimacy check with an + /// interdiction band that fails, and `appoint` makes succession an act + /// someone performs under authority rather than a declared method string. + #[test] + fn sanction_and_appoint_reach_the_reducer_under_authority() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = civics(directory.path(), "Institutional"); + let treasury = bench.civic.treasury; + let passage = bench.civic.passage; + let sanction = bench.call( + "sanction", + vec![binding("road", Target::Edge(passage))], + vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + None, + ); + + // The reeve holds the verb but its office lends only `levy`, so the same + // act names the precondition it failed. + assert_eq!( + bench.rejected_as(bench.civic.reeve, &sanction), + vec![ActionMismatch::NotAuthorized { precondition: 0 }] + ); + + // The treasury commands the hall, and the passage has both endpoints + // under it. The draw decides whether the interdiction lands. + let opportunity = opportunity_for(&bench.active, treasury); + let closing = (0..256) + .map(|_| CommandId::issue()) + .find(|candidate| { + draw_once(&bench.kernel.state, *candidate, &opportunity, &sanction) + .expect("the invocation is admissible") + .band + == 0 + }) + .expect("a two-band entry reaches its first band over 256 command ids"); + let caller = CallerId::Controller(opportunity.controller_id); + let receipt = bench + .kernel + .submit( + command( + &bench.active, + closing, + caller.clone(), + CommandBody::ExerciseDecision { + opportunity, + invocation: sanction, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .expect("the sanction commits"); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + bench.refresh(); + assert!(!bench.kernel.state.edges[&passage].is_open()); + + // Appointment installs an incumbent through the action lane. + let farmer = bench.civic.farmer; + let appoint = bench.call( + "appoint", + vec![ + binding("institution", Target::Subject(treasury)), + binding("candidate", Target::Subject(farmer)), + ], + vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + None, + ); + assert!(matches!( + bench.commit_as(treasury, appoint), + SubmitReceipt::Applied(_) + )); + assert_eq!( + bench.kernel.state.selection[&treasury][&office("bailiff")].incumbent, + Some(farmer) + ); + } + + // --- Soul: pass-5 falsification ------------------------------------- + + /// Submits an invocation through the real command path and hands back + /// whatever the kernel decided, refusal included. + fn soul_submit( + bench: &mut Civics, + actor: SubjectId, + invocation: DecisionInvocation, + ) -> Result { + let opportunity = opportunity_for(&bench.active, actor); + let caller = CallerId::Controller(opportunity.controller_id); + bench.kernel.submit( + command( + &bench.active, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + opportunity, + invocation, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + } + + /// `DelegationNotMonotone` is not a fixture-only verdict: the real `submit` + /// path reaches it, and the refused act commits nothing. + #[test] + fn soul_delegation_not_monotone_reaches_the_real_command_path() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = civics(directory.path(), "SoulMonotone"); + let treasury = bench.civic.treasury; + let road = bench.topology.road; + let outsider = bench.civic.outsider; + bench.admit(vec![grant_to(treasury, COMMAND_KIND, over_place(road))]); + let invocation = bench.delegate(outsider, road); + let before = bench.kernel.state.clone(); + let error = soul_submit(&mut bench, treasury, invocation).unwrap_err(); + let KernelError::ActionRejected(rejected) = error else { + panic!("an over-wide delegation is an action rejection"); + }; + assert_eq!( + rejected, + vec![ActionMismatch::DelegationNotMonotone { slot: 0 }] + ); + assert_eq!(bench.kernel.state.revision, before.revision); + assert_eq!(bench.kernel.state.authority, before.authority); + assert_eq!(bench.kernel.state.events.len(), before.events.len()); + } + + /// The `Restricted` rule is enforced by the component writer, not only by + /// the resolver: a forged `ResolvedOp` that skipped `resolve_patch` still + /// cannot walk a subject through a door it holds no key to, and the same + /// operation succeeds the moment the key exists. + #[test] + fn soul_a_restricted_relocate_is_refused_by_the_component_writer() { + let directory = tempfile::tempdir().unwrap(); + let bench = civics(directory.path(), "SoulReducerGate"); + let walker = bench.topology.walker; + let step = ResolvedOp::Relocate { + subject_id: walker, + edge_id: bench.civic.postern, + }; + + let mut forged = bench.kernel.state.clone(); + forged.positions.insert( + walker, + crate::patch::Position { + place: bench.topology.yard, + }, + ); + let mut refused = forged.clone(); + let resolves_to = refused.revision + 1; + let error = + crate::apply_operations(&mut refused, std::slice::from_ref(&step), &[], resolves_to) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_))); + + let mut admitted = forged; + admitted.authority.insert( + walker, + BTreeSet::from([crate::AuthorityGrant { + kind: crate::tests::authority_kind(ADMIT_KIND), + over: crate::AuthorityTarget::PlaceSubtree(bench.civic.hall), + }]), + ); + let resolves_to = admitted.revision + 1; + crate::apply_operations(&mut admitted, std::slice::from_ref(&step), &[], resolves_to) + .expect("the named key opens the door at the component writer too"); + assert_eq!(admitted.positions[&walker].place, bench.civic.chamber); + } + + /// The rebind requirement at the layer the operator sees it: a grant change + /// on the *granter* invalidates the delegate's bound opportunity, and the + /// refusal is `ScopeChanged`, not `ActionRejected`. + #[test] + fn soul_a_granter_revocation_rebinds_the_delegate() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = civics(directory.path(), "SoulRebind"); + let reeve = bench.civic.reeve; + let farmer = bench.civic.farmer; + let treasury = bench.civic.treasury; + let hall = bench.civic.hall; + + // Bound before the revocation, submitted after it. + let bound = bench.active.clone(); + let opportunity = opportunity_for(&bound, reeve); + let caller = CallerId::Controller(opportunity.controller_id); + let invocation = bench.levy(farmer, 1); + bench.admit(vec![ComponentOp::RevokeAuthority { + holder: PatchRef::Existing(treasury), + grant: crate::tests::grant_of(LEVY_KIND, over_place(hall)), + }]); + // The envelope carries the current revision, so only the stale scope + // digest can refuse it. + assert_ne!(bound.revision, bench.active.revision); + let error = bench + .kernel + .submit( + command( + &bench.active, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + opportunity, + invocation, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .unwrap_err(); + assert!( + matches!(error, KernelError::ScopeChanged { .. }), + "a revoked lend is a rebind, not a rejection: {error:?}" + ); + } + + /// Structural overlap alone does not see a `Subject` grant sitting inside + /// a `PlaceSubtree` grant of the same kind: `targets_overlap` compares + /// shapes, not position, and stays that way so the answer cannot decay + /// when a subject walks somewhere. Admission catches the cross-shape case + /// live instead, in the resolver where the second grant lands, using the + /// same covering predicate `Authorized` reads. Both directions fire the + /// identical check, so whichever grant is minted second is the one that + /// is refused. + #[test] + fn soul_a_subject_grant_inside_a_place_grant_is_a_second_source() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = civics(directory.path(), "SoulOverlap"); + let treasury = bench.civic.treasury; + let farmer = bench.civic.farmer; + let hall = bench.civic.hall; + + // The farmer stands under the hall the treasury already levies, so the + // covering predicate says both grants would answer for the same + // target, and admission refuses the narrower grant landing second. + assert!(crate::covers( + &bench.kernel.state, + crate::AuthorityTarget::PlaceSubtree(hall), + Target::Subject(farmer) + )); + assert_eq!( + bench.refuse(vec![grant_to(treasury, LEVY_KIND, over_subject(farmer))]), + vec![crate::Mismatch::OverlappingJurisdiction { operation: 0 }] + ); + + // The symmetric order: a direct grant over the farmer, minted first + // under a fresh kind, blocks a later place grant that would cover + // him too. + const AUDIT_KIND: &str = "audit"; + bench.admit(vec![grant_to(treasury, AUDIT_KIND, over_subject(farmer))]); + assert_eq!( + bench.refuse(vec![grant_to(treasury, AUDIT_KIND, over_place(hall))]), + vec![crate::Mismatch::OverlappingJurisdiction { operation: 0 }] + ); + } + + /// Replay for the new arms is not a separate machine: `reduce` is a pure + /// function of committed state and the envelope, so running it twice on the + /// same pre-state yields the same effect, and that effect is exactly what + /// the commit stored. No clock and no draw entropy enter. + #[test] + fn soul_reduce_is_pure_for_every_new_civic_arm() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = civics(directory.path(), "SoulReplay"); + let treasury = bench.civic.treasury; + let farmer = bench.civic.farmer; + let outsider = bench.civic.outsider; + let chamber = bench.civic.chamber; + let passage = bench.civic.passage; + + let sanction = bench.call( + "sanction", + vec![binding("road", Target::Edge(passage))], + vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + None, + ); + let appoint = bench.call( + "appoint", + vec![ + binding("institution", Target::Subject(treasury)), + binding("candidate", Target::Subject(farmer)), + ], + vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + None, + ); + for invocation in [ + bench.levy(farmer, 2), + bench.delegate(outsider, chamber), + sanction, + appoint, + ] { + let before = bench.kernel.state.clone(); + let opportunity = opportunity_for(&bench.active, treasury); + let caller = CallerId::Controller(opportunity.controller_id); + let envelope = command( + &bench.active, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + opportunity, + invocation, + }, + ); + let first = crate::reduce(&before, &envelope).expect("the act reduces"); + let second = crate::reduce(&before, &envelope).expect("the act reduces again"); + assert_eq!(first, second, "reduce is not a pure function of the state"); + let receipt = bench + .kernel + .submit(envelope, &AuthenticatedCaller::fixture(caller)) + .expect("the act commits"); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + bench.refresh(); + let WorldEffect::DecisionExercised { event, .. } = first else { + panic!("an exercised decision"); + }; + assert_eq!( + bench.kernel.state.events.last().expect("a committed event"), + &event, + "the committed event is not what reduce produced" + ); + } + } + + /// `resolve_patch`'s candidate knowledge map never models `Communicate`'s + /// fan-out (see the comment beside its construction in `patch.rs`), and + /// that omission is safe only because no `ComponentOpKind` an affordance + /// may declare can lower to a knowledge write carrying + /// `KnowledgeSource::Told`. Two kinds touch knowledge: `AcquireKnowledge`, + /// whose source `lower` fixes to `AuthoredSource::Witnessed` — a type with + /// no `Told` variant to begin with — and `Witness`, which carries no source + /// field and no speaker field at all. This test pins both lowerings, at the + /// call sites that turn a declared slot into a `ComponentOp`, so a future + /// author cannot widen either without this assertion naming the change. + #[test] + fn no_component_op_kind_lowers_to_a_told_knowledge_write() { + let directory = tempfile::tempdir().unwrap(); + let bench = bench(directory.path(), "AcquireKnowledgeLowering"); + let entry = Affordance { + kind: AffordanceKindName("witness".into()), + roles: Vec::new(), + preconditions: Vec::new(), + effect_slots: vec![EffectSlot { + op_kind: ComponentOpKind::AcquireKnowledge { + confidence: Confidence::Believed, + }, + roles: vec![Role("subject".into()), Role("fact".into())], + bounds: Bounds::None, + }], + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: vec![0], + }], + carries_speech: false, + }; + let bindings = BTreeMap::from([ + (Role("subject".into()), Target::Subject(bench.clerk)), + (Role("fact".into()), Target::Entity(bench.tithe)), + ]); + let invocation = DecisionInvocation { + affordance: bench.carry, + bindings: Vec::new(), + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + speech: None, + display: None, + }; + let lowered = lower( + &entry, + 0, + bench.clerk, + FictionalMinutes::default(), + &invocation, + &bindings, + ) + .expect("the acquire slot lowers"); + assert_eq!( + lowered, + vec![ComponentOp::AcquireKnowledge { + subject: PatchRef::Existing(bench.clerk), + fact: PatchRef::Existing(bench.tithe), + source: AuthoredSource::Witnessed, + confidence: Confidence::Believed, + }], + "AcquireKnowledge must lower with a Witnessed source, never a forged teller" + ); + + let witnessing = Affordance { + kind: AffordanceKindName("beacon".into()), + roles: Vec::new(), + preconditions: Vec::new(), + effect_slots: vec![EffectSlot { + op_kind: ComponentOpKind::Witness { + confidence: Confidence::Believed, + }, + roles: vec![Role("fact".into()), Role("place".into())], + bounds: Bounds::None, + }], + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: vec![0], + }], + carries_speech: false, + }; + let places = BTreeMap::from([ + (Role("fact".into()), Target::Entity(bench.tithe)), + (Role("place".into()), Target::Entity(bench.yard)), + ]); + let lowered = lower( + &witnessing, + 0, + bench.clerk, + FictionalMinutes::default(), + &invocation, + &places, + ) + .expect("the witness slot lowers"); + assert_eq!( + lowered, + vec![ComponentOp::Witness { + fact: PatchRef::Existing(bench.tithe), + place: PatchRef::Existing(bench.yard), + confidence: Confidence::Believed, + }], + "Witness must lower with no speaker field to forge" + ); + } + + /// The pin above names two knowledge-touching kinds by example, and a list + /// by example goes stale in silence. This match is exhaustive, so a new + /// `ComponentOpKind` breaks the build here and its author must say whether + /// it touches knowledge. The set that does is `AcquireKnowledge`, `Witness`, + /// and `Forget`; the first two are pinned above as unable to carry a teller, + /// and `Forget` writes no row at all — it only removes one, so it has no + /// source to forge. + #[test] + fn soul_every_knowledge_touching_op_kind_is_named_by_the_told_pin() { + fn touches_knowledge(kind: &ComponentOpKind) -> bool { + match kind { + ComponentOpKind::AcquireKnowledge { .. } + | ComponentOpKind::Witness { .. } + | ComponentOpKind::Forget => true, + ComponentOpKind::Relocate + | ComponentOpKind::OpenRoute + | ComponentOpKind::CloseRoute + | ComponentOpKind::AlterCost + | ComponentOpKind::Transfer + | ComponentOpKind::Transform + | ComponentOpKind::Consume + | ComponentOpKind::Bind + | ComponentOpKind::Release + | ComponentOpKind::GrantAuthority { .. } + | ComponentOpKind::RevokeAuthority { .. } + | ComponentOpKind::InstallIncumbent { .. } + | ComponentOpKind::VacateOffice { .. } + | ComponentOpKind::CreateCommitment { .. } + | ComponentOpKind::AdvancePressure { .. } + | ComponentOpKind::ReducePressure { .. } + | ComponentOpKind::ResolvePressure => false, + } + } + + let confidence = Confidence::Believed; + let touching = [ + ComponentOpKind::AcquireKnowledge { confidence }, + ComponentOpKind::Witness { confidence }, + ComponentOpKind::Forget, + ComponentOpKind::Relocate, + ComponentOpKind::Transfer, + ComponentOpKind::ResolvePressure, + ] + .iter() + .filter(|kind| touches_knowledge(kind)) + .count(); + assert_eq!( + touching, 3, + "the knowledge-touching set is not the one this pin names" + ); + } +} diff --git a/native/aetherlight/src/clock.rs b/native/aetherlight/src/clock.rs new file mode 100644 index 000000000..a02c21560 --- /dev/null +++ b/native/aetherlight/src/clock.rs @@ -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.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 { + (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, + /// Pressure rows written, in `(target, source)` order, with the resulting + /// magnitude — not the delta. + pub(crate) pressed: Vec, +} + +#[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 { + 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), + } +} diff --git a/native/aetherlight/src/cover.rs b/native/aetherlight/src/cover.rs new file mode 100644 index 000000000..5d1ce4233 --- /dev/null +++ b/native/aetherlight/src/cover.rs @@ -0,0 +1,1105 @@ +//! The budgeted connected cover: one tick's partition of the active +//! opportunities into cells. +//! +//! This organ owns the partition and nothing else. [`derive_cover`] is pure +//! over its arguments — no clock, no entropy, no mailbox, no filesystem — and +//! the [`Cover`] it returns is derived and disposable. A cell never enters +//! `WorldState`, a `CommandEnvelope`, a `ScopePreimage`, a `DecisionOpportunity`, +//! or any `Declaration`; the kernel never learns a tick happened except through +//! `AdvanceTime` and ordinary one-opportunity submissions. +//! +//! The cover is a partition, never a filter: every active subject is in exactly +//! one cell every tick. The budget decides at what resolution, not whether. + +use super::{ControllerMode, DecisionOpportunity, SubjectId, WorldId}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::collections::{BTreeMap, BTreeSet}; +use uuid::Uuid; + +/// A place, resource, or channel with more associated subjects than this +/// contributes a star centred on its lowest member instead of a clique. +/// Connectivity is identical for component purposes and the edge count stops +/// being quadratic in a crowded room. +pub(crate) const AGENCY_STAR_THRESHOLD: usize = 16; + +/// The namespace every derived cover id is salted with. A fixed constant, never +/// regenerated: two worlds in one process are separated by the world id inside +/// the name, not by a second namespace. +const COVER_NAMESPACE: &str = "ghostlight.cover.v1"; + +/// A tick's ordinal: the number of clock advances the world had committed when +/// the tick opened. The driver reads it from the world and freezes it in the +/// tick document; it is never derived from `now`, so it does not depend on the +/// span. It is threaded into every derived command id, so a resumed tick +/// re-submits the same ids and the kernel's idempotency ledger answers with the +/// original receipts instead of double-committing. +#[derive( + Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Default, +)] +#[serde(transparent)] +pub struct TickIndex(pub u64); + +/// How a subject was represented this tick. Derived from the cell, carried +/// nowhere in world state: representation is a compute budget, not world truth. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "resolution", rename_all = "snake_case")] +pub enum Resolution { + Detail, + Coarse { constituents: usize }, +} + +/// Derived from the partition, so a replayed tick over the same inputs produces +/// byte-identical ids. sha256 over `(namespace, world, tick, size, lowest +/// member)`; no `uuid/v5`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(transparent)] +pub struct CellId(Uuid); + +impl std::fmt::Display for CellId { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(formatter, "{}", self.0) + } +} + +fn derive_uuid(name: &str) -> Uuid { + let mut hasher = Sha256::new(); + hasher.update(COVER_NAMESPACE.as_bytes()); + hasher.update([0u8]); + hasher.update(name.as_bytes()); + let bytes: [u8; 16] = hasher.finalize()[..16] + .try_into() + .expect("sha256 yields at least sixteen bytes"); + Uuid::from_bytes(bytes) +} + +/// `members.len()` is in the name so a component that splits differently under +/// a different cap yields a different cell, and a resumed tick over the same +/// inputs yields the same one. +fn cell_id(world: WorldId, tick: TickIndex, members: &[SubjectId]) -> CellId { + let lowest = members + .first() + .copied() + .expect("a cell always has at least one member"); + CellId(derive_uuid(&format!( + "cell|{world:?}|{}|{}|{lowest:?}", + tick.0, + members.len() + ))) +} + +/// The stable, derived identity a cell's controller-work row is keyed by. +pub(crate) fn cell_work_uuid(world: WorldId, cell: CellId, tick: TickIndex) -> Uuid { + derive_uuid(&format!("cell-work|{world:?}|{cell}|{}", tick.0)) +} + +/// One constituent's submission id. Deterministic, so a resumed cell re-submits +/// the same id and the kernel answers from its idempotency ledger. +pub(crate) fn cell_constituent_uuid( + world: WorldId, + cell: CellId, + subject: SubjectId, + tick: TickIndex, +) -> Uuid { + derive_uuid(&format!("cell-act|{world:?}|{cell}|{subject:?}|{}", tick.0)) +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Constituent { + pub subject: SubjectId, + pub(crate) opportunity: DecisionOpportunity, +} + +/// One inference's worth of the world. A singleton keeps the detail path and its +/// membrane; a group is one inference over N labeled, never-unioned views. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Cell { + Singleton { + id: CellId, + tick: TickIndex, + member: Constituent, + }, + /// `members` is ascending by `SubjectId`; the index into it is the + /// constituent handle the model-facing tool names carry. + Group { + id: CellId, + tick: TickIndex, + members: Vec, + }, +} + +impl Cell { + pub(crate) fn members(&self) -> &[Constituent] { + match self { + Self::Singleton { member, .. } => std::slice::from_ref(member), + Self::Group { members, .. } => members, + } + } +} + +/// Derived, disposable, dropped at the end of a tick. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Cover { + pub tick: TickIndex, + pub cells: Vec, + /// True when the constituent cap could not hold every active subject inside + /// the cell budget, so the cap yielded and every cell grew. "Every active + /// subject is in the cover every tick" is an ontology invariant; the cap is + /// a prompt-size preference. Rendered read-only: it is the honest signal + /// that the world outgrew its prompt budget rather than a truncation nobody + /// sees. + pub oversubscribed: bool, +} + +impl Cover { + pub fn singletons(&self) -> usize { + self.cells + .iter() + .filter(|cell| matches!(cell, Cell::Singleton { .. })) + .count() + } + + pub fn groups(&self) -> usize { + self.cells.len() - self.singletons() + } +} + +/// How many inferences one tick may spend, and how large one prompt may get. +/// Two budgets, deliberately not one: only the second bounds tokens. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct CoverBudget { + /// B: cells per tick. + pub cells: u16, + /// C: the per-cell constituent cap. At least two, or a group is a singleton + /// with extra steps. + pub constituent_cap: u16, + /// U: singleton slots reserved for the head of the attention order. The + /// rest of the singleton slots carry the rotation window. + pub urgency_slots: u16, +} + +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +pub enum CoverBudgetError { + #[error("cover cell budget must be at least one")] + NoCells, + #[error("cover constituent cap must be at least two")] + CapTooSmall, +} + +impl CoverBudget { + pub fn validated(self) -> Result { + if self.cells < 1 { + return Err(CoverBudgetError::NoCells); + } + if self.constituent_cap < 2 { + return Err(CoverBudgetError::CapTooSmall); + } + Ok(self) + } +} + +/// The scheduler's own projection, wider than any subject view and reachable +/// from no prompt builder: it is constructed by the tick driver, handed to +/// [`derive_cover`], and dropped. `run_cell` takes a `&Cell`, which contains no +/// graph, so a controller organ that could read adjacency fails to compile +/// rather than failing a test. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct AgencyGraph { + /// Ascending. Exactly the subjects with a non-Human controller assignment. + pub(crate) subjects: Vec, + /// Undirected, canonicalised `(lo, hi)` with `lo < hi`. + pub(crate) edges: BTreeSet<(SubjectId, SubjectId)>, +} + +impl AgencyGraph { + /// A clique below the star threshold, a star above it. Connectivity for + /// component purposes is identical either way. + pub(crate) fn relate(&mut self, group: &BTreeSet) { + let members: Vec = group.iter().copied().collect(); + if members.len() < 2 { + return; + } + if members.len() > AGENCY_STAR_THRESHOLD { + let centre = members[0]; + for member in &members[1..] { + self.link(centre, *member); + } + return; + } + for (index, one) in members.iter().enumerate() { + for other in &members[index + 1..] { + self.link(*one, *other); + } + } + } + + pub(crate) fn link(&mut self, one: SubjectId, other: SubjectId) { + if one == other { + return; + } + let pair = if one < other { + (one, other) + } else { + (other, one) + }; + self.edges.insert(pair); + } +} + +/// The partition. Pure over `(world, tick, opportunities, graph, budget)`. +/// +/// `opportunities` arrives in the kernel's one attention order (pressure, then +/// attention debt, then id) and is never re-sorted and never filtered here: a +/// Human opportunity is skipped because a human turn is not an inference, which +/// is a fact about cognition rather than a scheduling preference. +pub fn derive_cover( + world: WorldId, + tick: TickIndex, + opportunities: &[DecisionOpportunity], + graph: &AgencyGraph, + budget: CoverBudget, +) -> Cover { + let active: Vec<&DecisionOpportunity> = opportunities + .iter() + .filter(|opportunity| opportunity.controller_mode != ControllerMode::Human) + .collect(); + let count = active.len(); + if count == 0 { + return Cover { + tick, + cells: Vec::new(), + oversubscribed: false, + }; + } + let constituent = |opportunity: &DecisionOpportunity| Constituent { + subject: opportunity.scope.subject_id, + opportunity: opportunity.clone(), + }; + let cell_budget = usize::from(budget.cells).max(1); + let cap = usize::from(budget.constituent_cap).max(2); + + if count <= cell_budget { + let cells = active + .iter() + .map(|opportunity| { + let member = constituent(opportunity); + Cell::Singleton { + id: cell_id(world, tick, &[member.subject]), + tick, + member, + } + }) + .collect(); + return Cover { + tick, + cells, + oversubscribed: false, + }; + } + + // Step 2. Group cells must hold the non-singletons under the cap: + // `K + ceil((N - K) / C) <= B`. The cap yields when no such partition + // exists, because coverage is the invariant and the cap is a preference. + let capacity = cap.saturating_mul(cell_budget); + let mut oversubscribed = capacity < count; + let (singleton_slots, effective_cap) = if oversubscribed { + (0usize, count.div_ceil(cell_budget)) + } else { + ((capacity - count) / (cap - 1), cap) + }; + let singleton_slots = singleton_slots.min(count); + let group_budget = cell_budget - singleton_slots; + + // Step 3. The rotation window. A stable order that does not move with + // pressure is what lets it carry a guarantee: a subject at index `i` is in + // the window exactly when `phase == i / R`, and `phase` cycles once every + // `ceil(N / R)` consecutive ticks because `now` only advances. + let urgency = usize::from(budget.urgency_slots).min(singleton_slots); + let reserve = singleton_slots - urgency; + let ascending: Vec = { + let mut ids: Vec = active + .iter() + .map(|opportunity| opportunity.scope.subject_id) + .collect(); + ids.sort_unstable(); + ids + }; + let mut chosen: BTreeSet = BTreeSet::new(); + if reserve > 0 { + let cycle = count.div_ceil(reserve); + let phase = usize::try_from(tick.0 % cycle as u64).unwrap_or(0); + let lo = phase * reserve; + let hi = (lo + reserve).min(count); + for subject in &ascending[lo.min(count)..hi] { + chosen.insert(*subject); + } + } + // Step 4. Urgency, then backfill in the attention order. A subject in both + // reserves consumes one slot, not two, and every slot is spent. + for opportunity in active.iter().take(urgency) { + chosen.insert(opportunity.scope.subject_id); + } + for opportunity in &active { + if chosen.len() >= singleton_slots { + break; + } + chosen.insert(opportunity.scope.subject_id); + } + + let mut cells: Vec = Vec::new(); + for opportunity in &active { + let subject = opportunity.scope.subject_id; + if !chosen.contains(&subject) { + continue; + } + let member = constituent(opportunity); + cells.push(Cell::Singleton { + id: cell_id(world, tick, &[subject]), + tick, + member, + }); + } + + // Step 5. Connected components over the remainder. + let rest: Vec<&DecisionOpportunity> = active + .iter() + .copied() + .filter(|opportunity| !chosen.contains(&opportunity.scope.subject_id)) + .collect(); + let rank: BTreeMap = active + .iter() + .enumerate() + .map(|(index, opportunity)| (opportunity.scope.subject_id, index)) + .collect(); + let mut groups = components(&rest, graph); + + // Step 6. A component larger than the cap is cut in id order. A chunk of a + // connected component is still a legitimate coarse group, and a graph-aware + // cut would be a second partitioning heuristic whose only payoff is + // adjacency inside a prompt that never mentions adjacency. + let mut split: Vec> = Vec::new(); + for component in groups.drain(..) { + for chunk in component.chunks(effective_cap) { + split.push(chunk.to_vec()); + } + } + + // Step 7. Merge the lowest-ranked cells until the group budget is met. The + // choke falls on the quietest cells; the highest-pressure groups keep the + // smallest, sharpest prompts. Priority is read from the attention order, + // which is its one owner — the scheduler computes no second ranking. + let priority = |members: &Vec| { + members + .iter() + .filter_map(|subject| rank.get(subject).copied()) + .min() + .unwrap_or(usize::MAX) + }; + split.sort_by_key(|members| (priority(members), members[0])); + let mut head = split.len(); + let mut packed: Vec> = Vec::new(); + let mut bucket: Vec = Vec::new(); + while head > 0 { + let open = usize::from(!bucket.is_empty()); + if head + packed.len() + open <= group_budget { + break; + } + head -= 1; + let component = split[head].clone(); + if !bucket.is_empty() && bucket.len() + component.len() > effective_cap { + packed.push(std::mem::take(&mut bucket)); + } + bucket.extend(component); + } + if !bucket.is_empty() { + packed.push(bucket); + } + split.truncate(head); + split.append(&mut packed); + // Component sizes need not pack perfectly into the cap, so the packing pass + // can end above budget. The cap yields here for the same reason it yields in + // step 2: coverage is the invariant, prompt size is the preference, and the + // operator is told rather than shown a silent truncation. + while split.len() > group_budget && split.len() >= 2 { + split.sort_by_key(|members| (priority(members), members[0])); + let last = split.pop().expect("two or more cells were established"); + let previous = split.pop().expect("two or more cells were established"); + let mut merged = previous; + merged.extend(last); + split.push(merged); + oversubscribed = true; + } + + for members in &mut split { + members.sort_unstable(); + } + split.sort_by_key(|members| (priority(members), members[0])); + let by_subject: BTreeMap = rest + .iter() + .map(|opportunity| (opportunity.scope.subject_id, *opportunity)) + .collect(); + for members in split { + let constituents: Vec = members + .iter() + .filter_map(|subject| by_subject.get(subject).map(|entry| constituent(entry))) + .collect(); + if constituents.is_empty() { + continue; + } + cells.push(Cell::Group { + id: cell_id(world, tick, &members), + tick, + members: constituents, + }); + } + + debug_assert_eq!( + cells + .iter() + .flat_map(Cell::members) + .map(|member| member.subject) + .collect::>() + .len(), + count, + "the cover is a partition: every active subject appears exactly once" + ); + debug_assert!(cells.len() <= cell_budget, "the cover respects its budget"); + + Cover { + tick, + cells, + oversubscribed, + } +} + +/// Union-find over the remainder's induced subgraph. Deterministic by +/// construction: a `BTreeSet` of edges in `SubjectId` order, components keyed by +/// their lowest member, members ascending. +fn components(rest: &[&DecisionOpportunity], graph: &AgencyGraph) -> Vec> { + let present: BTreeSet = rest + .iter() + .map(|opportunity| opportunity.scope.subject_id) + .collect(); + let mut parent: BTreeMap = + present.iter().map(|subject| (*subject, *subject)).collect(); + + fn find(parent: &mut BTreeMap, node: SubjectId) -> SubjectId { + let mut root = node; + while let Some(next) = parent.get(&root).copied() { + if next == root { + break; + } + root = next; + } + let mut cursor = node; + while let Some(next) = parent.get(&cursor).copied() { + if next == cursor { + break; + } + parent.insert(cursor, root); + cursor = next; + } + root + } + + for (one, other) in &graph.edges { + if !present.contains(one) || !present.contains(other) { + continue; + } + let left = find(&mut parent, *one); + let right = find(&mut parent, *other); + if left != right { + let (low, high) = if left < right { + (left, right) + } else { + (right, left) + }; + parent.insert(high, low); + } + } + + let mut buckets: BTreeMap> = BTreeMap::new(); + for subject in &present { + let root = find(&mut parent, *subject); + buckets.entry(root).or_default().push(*subject); + } + buckets + .into_values() + .map(|mut members| { + members.sort_unstable(); + members + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{DecisionScope, ScopeDigest}; + + fn subject(index: u128) -> SubjectId { + serde_json::from_value(serde_json::json!(Uuid::from_u128(index).to_string())) + .expect("a subject id parses from its canonical uuid") + } + + fn opportunity(index: u128, mode: ControllerMode) -> DecisionOpportunity { + let subject_id = subject(index); + DecisionOpportunity { + world_id: WorldId::nil_for_test(), + revision: 1, + scope_digest: ScopeDigest::fixture(&format!("scope-{index}")), + scope: DecisionScope { subject_id }, + controller_id: serde_json::from_value(serde_json::json!( + Uuid::from_u128(index + 1_000_000).to_string() + )) + .expect("a controller id parses from its canonical uuid"), + controller_mode: mode, + affordance_ids: Vec::new(), + } + } + + fn active(count: u128) -> Vec { + (1..=count) + .map(|index| opportunity(index, ControllerMode::OperationalAgent)) + .collect() + } + + fn budget(cells: u16, cap: u16, urgency: u16) -> CoverBudget { + CoverBudget { + cells, + constituent_cap: cap, + urgency_slots: urgency, + } + } + + fn covered(cover: &Cover) -> Vec { + let mut subjects: Vec = cover + .cells + .iter() + .flat_map(Cell::members) + .map(|member| member.subject) + .collect(); + subjects.sort_unstable(); + subjects + } + + fn derive( + opportunities: &[DecisionOpportunity], + graph: &AgencyGraph, + budget: CoverBudget, + tick: u64, + ) -> Cover { + derive_cover( + WorldId::nil_for_test(), + TickIndex(tick), + opportunities, + graph, + budget, + ) + } + + /// Verification 21, at the design profile: 2,400 subjects, 240 cells, a cap + /// of 24, 36 urgency slots. Every subject exactly once, the budget held, and + /// the head of the attention order attended in detail. + #[test] + fn soul_the_design_profile_covers_every_subject_exactly_once_inside_its_budget() { + let opportunities = active(2_400); + let cover = derive( + &opportunities, + &AgencyGraph::default(), + budget(240, 24, 36), + 0, + ); + + assert_eq!(covered(&cover).len(), 2_400); + assert_eq!( + covered(&cover).iter().collect::>().len(), + 2_400, + "no subject is covered twice" + ); + assert!(cover.cells.len() <= 240); + assert!(!cover.oversubscribed); + // K = floor((24*240 - 2400) / 23) = 146 singleton slots. + assert_eq!(cover.singletons(), 146); + assert_eq!(cover.groups(), 94); + assert!( + cover.cells.iter().all(|cell| cell.members().len() <= 24), + "no cell exceeds the constituent cap" + ); + + let head = opportunities[0].scope.subject_id; + let urgent: BTreeSet = opportunities[..36] + .iter() + .map(|entry| entry.scope.subject_id) + .collect(); + let singletons: BTreeSet = cover + .cells + .iter() + .filter_map(|cell| match cell { + Cell::Singleton { member, .. } => Some(member.subject), + Cell::Group { .. } => None, + }) + .collect(); + assert!( + singletons.contains(&head), + "the head of the order is a singleton" + ); + assert!( + urgent.is_subset(&singletons), + "every urgency slot is spent on the head of the order" + ); + } + + /// A human opportunity is not an inference. It is skipped, and skipping it + /// is not a filter on the cover: it never was a candidate. + #[test] + fn a_human_opportunity_is_never_in_a_cell() { + let opportunities = vec![ + opportunity(1, ControllerMode::Human), + opportunity(2, ControllerMode::OperationalAgent), + opportunity(3, ControllerMode::NarrativePersona), + ]; + let cover = derive(&opportunities, &AgencyGraph::default(), budget(8, 4, 1), 0); + assert_eq!(covered(&cover), vec![subject(2), subject(3)]); + } + + /// Below the budget every opportunity is its own cell and the detail path is + /// untouched. + #[test] + fn a_small_world_is_all_singletons() { + let opportunities = active(5); + let cover = derive( + &opportunities, + &AgencyGraph::default(), + budget(240, 24, 36), + 0, + ); + assert_eq!(cover.singletons(), 5); + assert_eq!(cover.groups(), 0); + assert!(!cover.oversubscribed); + } + + /// The cap yields, the budget does not. Every subject is still covered + /// exactly once and the operator learns the world outgrew the prompt bound. + #[test] + fn soul_an_oversubscribed_world_relaxes_the_cap_rather_than_dropping_a_subject() { + let opportunities = active(100); + let cover = derive(&opportunities, &AgencyGraph::default(), budget(10, 4, 2), 0); + assert!(cover.oversubscribed); + assert_eq!(covered(&cover).len(), 100); + assert_eq!(covered(&cover).iter().collect::>().len(), 100); + assert!(cover.cells.len() <= 10); + assert_eq!(cover.singletons(), 0, "no slot is spent on detail here"); + } + + /// The fairness arithmetic, with no persisted field behind it: a subject + /// continuously active for `ceil(N / R)` ticks is a singleton at least once. + #[test] + fn soul_every_subject_reaches_a_singleton_within_the_rotation_window() { + // N = 25, B = 12, C = 8, U = 1 → K = floor((96 - 25) / 7) = 10, R = 9. + let opportunities = active(25); + let budget = budget(12, 8, 1); + let cycle = 25usize.div_ceil(9); + let mut seen: BTreeSet = BTreeSet::new(); + for tick in 0..cycle as u64 { + let cover = derive(&opportunities, &AgencyGraph::default(), budget, tick); + for cell in &cover.cells { + if let Cell::Singleton { member, .. } = cell { + seen.insert(member.subject); + } + } + } + let all: BTreeSet = opportunities + .iter() + .map(|entry| entry.scope.subject_id) + .collect(); + assert_eq!(seen, all, "the window closes over every subject"); + } + + /// A narrow reserve still closes, it just takes longer. The guarantee is + /// `ceil(N / R)`, never `ceil(N / B)`: giving every cell to a singleton + /// would leave subjects out of the cover, which the ontology forbids. + #[test] + fn the_rotation_guarantee_is_over_the_reserve_not_the_cell_budget() { + let opportunities = active(25); + // K = floor((8*10 - 25) / 7) = 7, U = 6 → R = 1, cycle = 25. + let budget = budget(10, 8, 6); + let mut seen: BTreeSet = BTreeSet::new(); + for tick in 0..25u64 { + let cover = derive(&opportunities, &AgencyGraph::default(), budget, tick); + for cell in &cover.cells { + if let Cell::Singleton { member, .. } = cell { + seen.insert(member.subject); + } + } + } + assert_eq!(seen.len(), 25); + } + + /// The cover is derived, not remembered: the same inputs yield the same + /// partition, the same ids, and the same order. + #[test] + fn soul_the_same_inputs_derive_an_identical_partition() { + let opportunities = active(60); + let mut graph = AgencyGraph::default(); + graph.link(subject(3), subject(4)); + graph.link(subject(4), subject(5)); + let one = derive(&opportunities, &graph, budget(10, 8, 2), 7); + let other = derive(&opportunities, &graph, budget(10, 8, 2), 7); + assert_eq!(one, other); + } + + /// Connected subjects land in one cell when the budget allows it. + #[test] + fn a_connected_component_becomes_one_coarse_cell() { + let opportunities = active(20); + let mut graph = AgencyGraph::default(); + for index in 10..20 { + graph.link(subject(10), subject(index)); + } + let cover = derive(&opportunities, &graph, budget(4, 12, 0), 0); + let component: BTreeSet = (10..20).map(subject).collect(); + let together = cover.cells.iter().any(|cell| { + let members: BTreeSet = + cell.members().iter().map(|entry| entry.subject).collect(); + component.is_subset(&members) + }); + assert!(together, "one component was not split across cells"); + } + + /// Property sweep: the budget and the cap hold, and coverage is exact. + #[test] + fn soul_cell_count_and_cap_hold_across_profiles() { + for count in [1u128, 3, 7, 25, 100, 401] { + for cells in [1u16, 2, 5, 12, 240] { + for cap in [2u16, 3, 8, 24] { + let opportunities = active(count); + let cover = derive( + &opportunities, + &AgencyGraph::default(), + budget(cells, cap, 3), + 11, + ); + assert!( + cover.cells.len() <= usize::from(cells), + "count {count} cells {cells} cap {cap} exceeded its budget" + ); + assert_eq!( + covered(&cover).len(), + usize::try_from(count).expect("a test fixture fits usize"), + "count {count} cells {cells} cap {cap} lost a subject" + ); + if usize::from(cap) * usize::from(cells) + >= usize::try_from(count).expect("a test fixture fits usize") + { + assert!(!cover.oversubscribed); + assert!( + cover + .cells + .iter() + .all(|cell| cell.members().len() <= usize::from(cap)), + "count {count} cells {cells} cap {cap} exceeded the cap" + ); + } else { + assert!(cover.oversubscribed); + } + } + } + } + } + + /// A crowded referent contributes a star, not a clique: connectivity is the + /// same and the edge count stops being quadratic. + #[test] + fn a_crowded_referent_relates_as_a_star() { + let crowd: BTreeSet = (1..=40).map(subject).collect(); + let mut graph = AgencyGraph::default(); + graph.relate(&crowd); + assert_eq!(graph.edges.len(), 39); + + let small: BTreeSet = (1..=4).map(subject).collect(); + let mut clique = AgencyGraph::default(); + clique.relate(&small); + assert_eq!(clique.edges.len(), 6); + } + + /// Derived ids are a pure function of their tuple, and distinct tuples do + /// not collide. + #[test] + fn derived_ids_are_pure_and_distinct() { + let world = WorldId::nil_for_test(); + let cell = cell_id(world, TickIndex(4), &[subject(1), subject(2)]); + assert_eq!( + cell, + cell_id(world, TickIndex(4), &[subject(1), subject(2)]) + ); + assert_ne!( + cell, + cell_id(world, TickIndex(5), &[subject(1), subject(2)]) + ); + assert_ne!(cell, cell_id(world, TickIndex(4), &[subject(1)])); + + assert_eq!( + cell_constituent_uuid(world, cell, subject(1), TickIndex(4)), + cell_constituent_uuid(world, cell, subject(1), TickIndex(4)) + ); + assert_ne!( + cell_constituent_uuid(world, cell, subject(1), TickIndex(4)), + cell_constituent_uuid(world, cell, subject(2), TickIndex(4)) + ); + assert_ne!( + cell_constituent_uuid(world, cell, subject(1), TickIndex(4)), + cell_work_uuid(world, cell, TickIndex(4)) + ); + } + + #[test] + fn a_budget_without_cells_or_with_a_singleton_cap_is_refused() { + assert_eq!(budget(0, 4, 0).validated(), Err(CoverBudgetError::NoCells)); + assert_eq!( + budget(4, 1, 0).validated(), + Err(CoverBudgetError::CapTooSmall) + ); + assert!(budget(4, 2, 0).validated().is_ok()); + } + + /// The rotation guarantee at the design profile rather than at a toy size. + /// `K = 146`, `U = 36`, so the reserve is `R = 110` and the window closes in + /// `ceil(2400 / 110) = 22` ticks. Membership is stable across the sweep, + /// which is the precondition the tight bound is stated under. + #[test] + fn soul_b_the_profile_rotation_closes_over_every_subject_in_ceil_n_over_reserve_ticks() { + let opportunities = active(2_400); + let budget = budget(240, 24, 36); + let reserve = 146 - 36; + let cycle = 2_400usize.div_ceil(reserve); + assert_eq!(cycle, 22, "the profile's window is not 22 ticks wide"); + + let mut seen: BTreeSet = BTreeSet::new(); + for tick in 0..cycle as u64 { + let cover = derive(&opportunities, &AgencyGraph::default(), budget, tick); + assert_eq!(cover.singletons(), 146); + for cell in &cover.cells { + if let Cell::Singleton { member, .. } = cell { + seen.insert(member.subject); + } + } + } + assert_eq!( + seen.len(), + 2_400, + "{} subjects never reached detail inside the window", + 2_400 - seen.len() + ); + + // One tick short of the cycle must not already close it, or the bound + // is being read off a coincidence rather than the arithmetic. + let mut short: BTreeSet = BTreeSet::new(); + for tick in 0..(cycle - 1) as u64 { + for cell in &derive(&opportunities, &AgencyGraph::default(), budget, tick).cells { + if let Cell::Singleton { member, .. } = cell { + short.insert(member.subject); + } + } + } + assert!(short.len() < 2_400, "the window closed a tick early"); + } + + /// The urgency slots go to the head of the attention order the kernel + /// already owns, and the rotation window goes to ascending id order. The + /// fixture arrives in descending id order so the two rankings cannot be + /// confused with each other, and no third ranking exists to explain the + /// result. + #[test] + fn soul_b_urgency_slots_follow_the_attention_order_not_the_id_order() { + let mut opportunities = active(40); + opportunities.reverse(); + // N = 40, B = 10, C = 8 → K = floor((80 - 40) / 7) = 5, U = 3, R = 2. + let cover = derive(&opportunities, &AgencyGraph::default(), budget(10, 8, 3), 0); + let singletons: BTreeSet = cover + .cells + .iter() + .filter_map(|cell| match cell { + Cell::Singleton { member, .. } => Some(member.subject), + Cell::Group { .. } => None, + }) + .collect(); + assert_eq!(singletons.len(), 5); + + let head: BTreeSet = opportunities[..3] + .iter() + .map(|entry| entry.scope.subject_id) + .collect(); + assert!( + head.is_subset(&singletons), + "the urgency slots did not follow the attention order" + ); + // The window is the ascending-id reserve, which here is the tail of the + // attention order: two rankings, both honoured, neither invented. + assert!( + singletons.contains(&subject(1)) && singletons.contains(&subject(2)), + "the rotation window did not follow ascending id order" + ); + } + + /// The partition is a pure function of its arguments, and the attention + /// order is one of those arguments rather than an incidental input. Equal + /// inputs derive an equal cover; a permuted order derives a different one, + /// because urgency and backfill read that order and `order_opportunities` + /// is its one owner. + #[test] + fn soul_b_the_cover_is_pure_and_the_attention_order_is_a_real_input() { + let opportunities = active(40); + let mut graph = AgencyGraph::default(); + graph.link(subject(11), subject(12)); + let budget = budget(10, 8, 3); + let ids = |cover: &Cover| -> Vec { + cover + .cells + .iter() + .map(|cell| match cell { + Cell::Singleton { id, .. } | Cell::Group { id, .. } => *id, + }) + .collect() + }; + + let one = derive(&opportunities, &graph, budget, 5); + let other = derive(&opportunities, &graph, budget, 5); + assert_eq!(one, other, "identical inputs derived different covers"); + assert_eq!( + serde_json::to_string(&ids(&one)).unwrap(), + serde_json::to_string(&ids(&other)).unwrap(), + "identical inputs derived different cell ids" + ); + + let mut reversed = opportunities.clone(); + reversed.reverse(); + let permuted = derive(&reversed, &graph, budget, 5); + assert_eq!( + covered(&one), + covered(&permuted), + "a permutation lost or duplicated a subject" + ); + let singletons = |cover: &Cover| -> BTreeSet { + cover + .cells + .iter() + .filter_map(|cell| match cell { + Cell::Singleton { member, .. } => Some(member.subject), + Cell::Group { .. } => None, + }) + .collect() + }; + assert_ne!( + singletons(&one), + singletons(&permuted), + "the attention order is not an input to the partition" + ); + // Coverage survives a permutation, but so does the sizing decision + // that partition made: shuffling the same subjects must not change + // how many cells they filled, only which subjects the singleton slots + // picked out. + assert_eq!( + one.cells.len(), + permuted.cells.len(), + "a permutation changed how many cells the same subjects filled" + ); + } + + /// Every cell in one cover carries that cover's tick index. This is what the + /// driver's "advance the clock after the cells" ordering buys: one `now`, + /// one phase, one set of derived command ids per tick. + #[test] + fn soul_b_every_cell_shares_the_covers_tick_index() { + let opportunities = active(60); + for tick in [0u64, 1, 7, 4_000] { + let cover = derive( + &opportunities, + &AgencyGraph::default(), + budget(10, 8, 2), + tick, + ); + assert_eq!(cover.tick, TickIndex(tick)); + for cell in &cover.cells { + let carried = match cell { + Cell::Singleton { tick, .. } | Cell::Group { tick, .. } => *tick, + }; + assert_eq!(carried, cover.tick, "a cell carried another tick's index"); + } + } + } + + /// Derived ids are collision-free across every cell of every tick in a full + /// sweep, and a cell key never collides with a constituent key. + #[test] + fn soul_b_derived_ids_do_not_collide_across_a_sweep_of_ticks() { + let world = WorldId::nil_for_test(); + let opportunities = active(600); + let budget = budget(60, 24, 6); + let mut cells: BTreeSet = BTreeSet::new(); + let mut keys: BTreeSet = BTreeSet::new(); + let mut cell_count = 0usize; + let mut key_count = 0usize; + for tick in 0..12u64 { + let cover = derive(&opportunities, &AgencyGraph::default(), budget, tick); + for cell in &cover.cells { + let id = match cell { + Cell::Singleton { id, .. } | Cell::Group { id, .. } => *id, + }; + cells.insert(id); + cell_count += 1; + keys.insert(cell_work_uuid(world, id, cover.tick)); + key_count += 1; + for member in cell.members() { + keys.insert(cell_constituent_uuid(world, id, member.subject, cover.tick)); + key_count += 1; + } + } + } + assert!( + cell_count >= 700, + "the sweep was too small to mean anything" + ); + assert_eq!(cells.len(), cell_count, "two cells share one id"); + assert_eq!(keys.len(), key_count, "two derived command keys collide"); + } + + /// The cap yields for exactly one reason: no partition inside the budget + /// respects it. Token capacity alone does not decide that — component shapes + /// do. Here `C * B = 12 >= N = 9`, and the cap still yields, because two + /// three-member components and two isolates cannot pack into two cells of + /// four. Coverage holds and the operator is told. + #[test] + fn soul_b_the_cap_yields_when_component_shapes_cannot_pack_inside_the_budget() { + let opportunities = active(9); + let mut graph = AgencyGraph::default(); + graph.link(subject(2), subject(3)); + graph.link(subject(3), subject(4)); + graph.link(subject(5), subject(6)); + graph.link(subject(6), subject(7)); + let cover = derive(&opportunities, &graph, budget(3, 4, 0), 0); + + assert_eq!(covered(&cover).len(), 9); + assert_eq!(covered(&cover).iter().collect::>().len(), 9); + assert!(cover.cells.len() <= 3); + assert!( + cover.cells.iter().any(|cell| cell.members().len() > 4), + "the cap did not yield: {:?}", + cover + .cells + .iter() + .map(|cell| cell.members().len()) + .collect::>() + ); + assert!( + cover.oversubscribed, + "the cap yielded without telling the operator" + ); + + // The same subjects with no edges pack cleanly and the flag stays down, + // so the flag tracks the partition rather than the subject count. + let loose = derive(&opportunities, &AgencyGraph::default(), budget(3, 4, 0), 0); + assert!(!loose.oversubscribed); + assert!(loose.cells.iter().all(|cell| cell.members().len() <= 4)); + } +} diff --git a/native/aetherlight/src/grammar.rs b/native/aetherlight/src/grammar.rs new file mode 100644 index 000000000..a11cd691a --- /dev/null +++ b/native/aetherlight/src/grammar.rs @@ -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, +} + +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 { + 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, +} + +#[derive(Deserialize)] +struct RawBinding { + schema_id: String, + revision: u32, + digest: String, + verbs: BTreeMap, +} + +impl TryFrom for GrammarBinding { + type Error = GrammarError; + + fn try_from(raw: RawBinding) -> Result { + 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, + revision: u32, + verbs: impl IntoIterator, + ) -> Result { + 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 { + 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 { + 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; diff --git a/native/aetherlight/src/grammar/tests.rs b/native/aetherlight/src/grammar/tests.rs new file mode 100644 index 000000000..85b3b1e19 --- /dev/null +++ b/native/aetherlight/src/grammar/tests.rs @@ -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, 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) -> WorldPatch { + WorldPatch { + declarations, + operations: Vec::new(), + evidence: Vec::new(), + } +} + +fn rejected(result: Result) -> Vec { + 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) { + 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 { + 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 { + vec![Mismatch::AffordanceKindNotInGrammar { + handle: DraftHandle::new(handle), + }] +} + +fn disagrees(handle: &str) -> Vec { + 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 = + 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::(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::(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::(&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, + patch: WorldPatch, +) -> Result { + 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); + +/// 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) { + 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}"); + } + } +} diff --git a/native/aetherlight/src/import_key_tests.rs b/native/aetherlight/src/import_key_tests.rs new file mode 100644 index 000000000..43ca2bb9a --- /dev/null +++ b/native/aetherlight/src/import_key_tests.rs @@ -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) { + 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) -> Vec { + 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) -> WorldPatch { + WorldPatch { + declarations, + operations: Vec::new(), + evidence: Vec::new(), + } +} + +fn submit_as( + kernel: &mut WorldKernel, + caller: CallerId, + answers: Option, + patch: WorldPatch, +) -> Result { + 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, 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 { + 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)>, +) { + 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 = 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 = "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" + ); +} diff --git a/native/aetherlight/src/journal.rs b/native/aetherlight/src/journal.rs new file mode 100644 index 000000000..a2d36fbb2 --- /dev/null +++ b/native/aetherlight/src/journal.rs @@ -0,0 +1,2990 @@ +use super::{ + COMMIT_SCHEMA, CommandId, CommittedCommand, KernelError, STATE_SCHEMA, WorldCommit, + WorldEffect, WorldId, WorldState, apply_effect, commit_digest, reduce, state_digest, +}; +use chrono::Utc; +use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore}; +use serde::{Serialize, de::DeserializeOwned}; +use std::{ + cell::Cell, + collections::{BTreeMap, BTreeSet}, + path::Path, +}; +use thiserror::Error; + +const STATE_ROW: &str = "world_state.elaboration.v1"; +const COMMIT_ROW: &str = "world_commit.elaboration.v1"; + +#[derive(Debug, Error)] +pub(super) enum JournalError { + #[error("opened store contains another world")] + WorldMismatch, + #[error("world ownership is uncertain after command {command_id:?}; drop and reopen")] + RecoveryRequired { command_id: CommandId }, + #[error("world store path no longer names the owned database")] + OwnershipLost, + #[error("world store operation failed: {0}")] + Store(String), + #[error("world journal is corrupt: {0}")] + Corrupt(String), +} + +pub(super) enum JournalOpen { + Empty(EmptyWorldJournal), + Live { + journal: WorldJournal, + state: WorldState, + }, +} + +pub(super) struct EmptyWorldJournal { + store: OwnedRedbMessagePackBackingStore, + #[cfg(test)] + fail_after_durable_initialize: bool, +} + +#[derive(Clone, Copy)] +enum JournalHealth { + Healthy, + RecoveryRequired(CommandId), + OwnershipLost, +} + +pub(super) struct WorldJournal { + store: OwnedRedbMessagePackBackingStore, + state_row: CultCacheEnvelope, + commits: BTreeMap, + health: Cell, + #[cfg(test)] + fail_after_durable_commit: bool, +} + +impl WorldJournal { + pub(super) fn open_owner(path: &Path) -> Result { + let store = OwnedRedbMessagePackBackingStore::new(path) + .map_err(|error| JournalError::Store(error.to_string()))?; + store + .validate_path_identity() + .map_err(|_| JournalError::OwnershipLost)?; + let rows = store + .pull_all() + .map_err(|error| JournalError::Store(error.to_string()))?; + store + .validate_path_identity() + .map_err(|_| JournalError::OwnershipLost)?; + if rows.is_empty() { + return Ok(JournalOpen::Empty(EmptyWorldJournal { + store, + #[cfg(test)] + fail_after_durable_initialize: false, + })); + } + let (state_row, state, commits) = recover(rows, None)?; + Ok(JournalOpen::Live { + journal: Self { + store, + state_row, + commits, + health: Cell::new(JournalHealth::Healthy), + #[cfg(test)] + fail_after_durable_commit: false, + }, + state, + }) + } + + pub(super) fn open( + path: &Path, + expected_world_id: WorldId, + ) -> Result<(Self, WorldState), JournalError> { + let store = OwnedRedbMessagePackBackingStore::new(path) + .map_err(|error| JournalError::Store(error.to_string()))?; + store + .validate_path_identity() + .map_err(|_| JournalError::OwnershipLost)?; + let rows = store + .pull_all() + .map_err(|error| JournalError::Store(error.to_string()))?; + store + .validate_path_identity() + .map_err(|_| JournalError::OwnershipLost)?; + let (state_row, state, commits) = recover(rows, Some(expected_world_id))?; + Ok(( + Self { + store, + state_row, + commits, + health: Cell::new(JournalHealth::Healthy), + #[cfg(test)] + fail_after_durable_commit: false, + }, + state, + )) + } + + pub(super) fn ensure_healthy(&self) -> Result<(), JournalError> { + match self.health.get() { + JournalHealth::RecoveryRequired(command_id) => { + return Err(JournalError::RecoveryRequired { command_id }); + } + JournalHealth::OwnershipLost => return Err(JournalError::OwnershipLost), + JournalHealth::Healthy => {} + } + if self.store.validate_path_identity().is_err() { + self.health.set(JournalHealth::OwnershipLost); + return Err(JournalError::OwnershipLost); + } + Ok(()) + } + + pub(super) fn commit( + &mut self, + next: &WorldState, + commit: &WorldCommit, + ) -> Result<(), JournalError> { + self.ensure_healthy()?; + let command_id = commit.command.id(); + if self.commits.contains_key(&command_id) { + return Err(JournalError::Corrupt( + "single-owner append attempted to duplicate a committed command".into(), + )); + } + let current: WorldState = decode(&self.state_row)?; + verify_append(¤t, next, commit)?; + let next_row = envelope(STATE_ROW, STATE_SCHEMA, next.world_id.key(), next)?; + let commit_row = envelope(COMMIT_ROW, COMMIT_SCHEMA, command_id.key(), commit)?; + self.health.set(JournalHealth::RecoveryRequired(command_id)); + let swapped = self.store.compare_and_swap_batch( + std::slice::from_ref(&self.state_row), + vec![next_row.clone(), commit_row], + ); + match swapped { + Ok(true) => {} + Ok(false) | Err(_) => { + return Err(JournalError::RecoveryRequired { command_id }); + } + } + #[cfg(test)] + if self.fail_after_durable_commit { + return Err(JournalError::RecoveryRequired { command_id }); + } + if self.store.validate_path_identity().is_err() { + return Err(JournalError::RecoveryRequired { command_id }); + } + self.state_row = next_row; + self.commits.insert(command_id, commit.clone()); + self.health.set(JournalHealth::Healthy); + Ok(()) + } + + pub(super) fn commit_for(&self, command_id: CommandId) -> Option<&WorldCommit> { + self.commits.get(&command_id) + } + + /// Every commit the journal holds, in no particular order. + pub(super) fn commits(&self) -> impl Iterator { + self.commits.values() + } + + #[cfg(test)] + pub(super) fn commit_count(&self) -> usize { + self.commits.len() + } + + /// PA.f40: a test outside this module needs the full commit map to forge + /// one commit's effect and route the forgery through `verify_history` + /// directly, the same way this module's own forgery tests already do via + /// `self.commits.clone()`. + #[cfg(test)] + pub(super) fn commits_for_test(&self) -> BTreeMap { + self.commits.clone() + } + + #[cfg(test)] + pub(super) fn fail_after_durable_commit_for_test(&mut self) { + self.fail_after_durable_commit = true; + } +} + +impl EmptyWorldJournal { + #[cfg(test)] + pub(super) fn fail_after_durable_initialize_for_test(&mut self) { + self.fail_after_durable_initialize = true; + } + + pub(super) fn initialize( + self, + state: &WorldState, + genesis: &WorldCommit, + ) -> Result { + self.store + .validate_path_identity() + .map_err(|_| JournalError::OwnershipLost)?; + let mut commits = BTreeMap::new(); + let command_id = genesis.command.id(); + commits.insert(command_id, genesis.clone()); + verify_history(state, &commits)?; + let state_row = envelope(STATE_ROW, STATE_SCHEMA, state.world_id.key(), state)?; + let commit_row = envelope(COMMIT_ROW, COMMIT_SCHEMA, command_id.key(), genesis)?; + let inserted = self + .store + .append_if_snapshot_unchanged(&[], vec![state_row.clone(), commit_row]); + if !matches!(inserted, Ok(true)) { + return Err(JournalError::RecoveryRequired { command_id }); + } + #[cfg(test)] + if self.fail_after_durable_initialize { + return Err(JournalError::RecoveryRequired { command_id }); + } + if self.store.validate_path_identity().is_err() { + return Err(JournalError::RecoveryRequired { command_id }); + } + Ok(WorldJournal { + store: self.store, + state_row, + commits, + health: Cell::new(JournalHealth::Healthy), + #[cfg(test)] + fail_after_durable_commit: false, + }) + } +} + +fn recover( + rows: Vec, + expected_world_id: Option, +) -> Result< + ( + CultCacheEnvelope, + WorldState, + BTreeMap, + ), + JournalError, +> { + let mut state_rows = Vec::new(); + let mut commits = BTreeMap::new(); + for row in rows { + match row.r#type.as_str() { + STATE_ROW => { + require_schema(&row, STATE_SCHEMA)?; + state_rows.push(row); + } + COMMIT_ROW => { + require_schema(&row, COMMIT_SCHEMA)?; + let commit: WorldCommit = decode(&row)?; + let command_id = commit.command.id(); + if row.key != command_id.key() { + return Err(JournalError::Corrupt( + "commit row key does not match command ID".into(), + )); + } + if commits.insert(command_id, commit).is_some() { + return Err(JournalError::Corrupt("duplicate command commit".into())); + } + } + other => { + return Err(JournalError::Corrupt(format!( + "unadmitted row type {other}" + ))); + } + } + } + if state_rows.len() != 1 { + return Err(JournalError::Corrupt(format!( + "expected one state row, found {}", + state_rows.len() + ))); + } + let state_row = state_rows.pop().expect("length checked"); + let state: WorldState = decode(&state_row)?; + if state_row.key != state.world_id.key() { + return Err(JournalError::Corrupt( + "state row key does not match its world ID".into(), + )); + } + if expected_world_id.is_some_and(|expected| state.world_id != expected) { + return Err(JournalError::WorldMismatch); + } + verify_history(&state, &commits)?; + Ok((state_row, state, commits)) +} + +fn verify_append( + current: &WorldState, + next: &WorldState, + commit: &WorldCommit, +) -> Result<(), JournalError> { + verify_state_shape(current)?; + verify_state_shape(next)?; + if current.world_id != next.world_id + || commit.world_id != current.world_id + || commit.schema != COMMIT_SCHEMA + || commit.previous_revision != Some(current.revision) + || commit.resulting_revision != next.revision + || next.revision != current.revision.saturating_add(1) + || commit.previous_state_digest.as_deref() != Some(current.state_digest.as_str()) + || commit.resulting_state_digest != next.state_digest + || commit.previous_commit_digest != current.last_commit_digest + || next.last_commit_digest.as_deref() != Some(commit.digest.as_str()) + { + return Err(JournalError::Corrupt( + "commit does not bind the exact state transition".into(), + )); + } + if state_digest(current).map_err(kernel_error)? != current.state_digest + || state_digest(next).map_err(kernel_error)? != next.state_digest + || commit_digest(commit).map_err(kernel_error)? != commit.digest + { + return Err(JournalError::Corrupt("digest mismatch".into())); + } + let mut replay = current.clone(); + apply_committed_command(&mut replay, commit)?; + replay.revision = next.revision; + replay.state_digest = state_digest(&replay).map_err(kernel_error)?; + replay.last_commit_digest = Some(commit.digest.clone()); + if &replay != next { + return Err(JournalError::Corrupt( + "commit effect does not reproduce next state".into(), + )); + } + Ok(()) +} + +/// `pub(super)`, matching `verify_state_shape`: a Soul-style forgery test +/// outside this module routes its falsification through the same function +/// that actually judges a committed history, rather than through the +/// structural-only `verify_state_shape`. +pub(super) fn verify_history( + state: &WorldState, + commits: &BTreeMap, +) -> Result<(), JournalError> { + verify_state_shape(state)?; + if commits + .iter() + .any(|(command_id, commit)| *command_id != commit.command.id()) + { + return Err(JournalError::Corrupt( + "commit index does not derive from the persisted command".into(), + )); + } + let expected_commits = usize::try_from(state.revision) + .map_err(|_| JournalError::Corrupt("revision does not fit this runtime".into()))?; + let expected_commits = expected_commits + .checked_add(1) + .ok_or_else(|| JournalError::Corrupt("commit count overflow".into()))?; + if commits.len() != expected_commits { + return Err(JournalError::Corrupt( + "commit count does not equal genesis plus head revision".into(), + )); + } + let mut ordered: Vec<_> = commits.values().collect(); + ordered.sort_by_key(|commit| commit.resulting_revision); + let genesis = ordered + .first() + .ok_or_else(|| JournalError::Corrupt("world has no genesis commit".into()))?; + let CommittedCommand::CreateWorld(genesis_command) = &genesis.command else { + return Err(JournalError::Corrupt( + "first commit does not contain the immutable creation command".into(), + )); + }; + let WorldEffect::WorldCreated { .. } = &genesis.effect else { + return Err(JournalError::Corrupt( + "first commit is not immutable world genesis".into(), + )); + }; + if genesis.schema != COMMIT_SCHEMA + || genesis.world_id != state.world_id + || genesis.previous_revision.is_some() + || genesis.resulting_revision != 0 + || genesis.previous_state_digest.is_some() + || genesis.previous_commit_digest.is_some() + || commit_digest(genesis).map_err(kernel_error)? != genesis.digest + { + return Err(JournalError::Corrupt( + "genesis commit is not canonical or verifiable".into(), + )); + } + let mut replay = WorldState::genesis(state.world_id, genesis_command, &genesis.effect) + .map_err(kernel_error)?; + verify_state_shape(&replay)?; + verify_commitments_are_future(&replay, &BTreeMap::new())?; + if replay.state_digest != genesis.resulting_state_digest { + return Err(JournalError::Corrupt( + "genesis resulting state digest is invalid".into(), + )); + } + replay.last_commit_digest = Some(genesis.digest.clone()); + + for commit in ordered.into_iter().skip(1) { + if commit.schema != COMMIT_SCHEMA + || commit.world_id != state.world_id + || commit.previous_revision != Some(replay.revision) + || commit.resulting_revision != replay.revision.saturating_add(1) + || commit.previous_state_digest.as_deref() != Some(replay.state_digest.as_str()) + || commit.previous_commit_digest != replay.last_commit_digest + || commit_digest(commit).map_err(kernel_error)? != commit.digest + { + return Err(JournalError::Corrupt( + "commit chain is not contiguous or verifiable".into(), + )); + } + let previous_now = replay.now; + let previous_commitments = replay.commitments.clone(); + // Authority is re-decided here for free: `apply_committed_command` + // re-runs `reduce` against the pre-commit state and requires effect + // equality, then `apply_effect`, and both of those call + // `require_patch_author` and `confine_to_jurisdiction`. A forged row + // claiming an elaborator caller for a patch outside its jurisdiction + // fails replay rather than being admitted by a reducer that trusts the + // recorded caller. A third statement of the same rule here would be a + // third owner of one decision. + apply_committed_command(&mut replay, commit)?; + // Two chain checks one state cannot make: the clock never runs + // backwards, and it advances only on a tick. + let advanced = matches!(commit.effect, WorldEffect::TimeAdvanced { .. }); + if replay.now < previous_now || (replay.now > previous_now) != advanced { + return Err(JournalError::Corrupt( + "the world clock moved without a time-advanced commit, or ran backwards".into(), + )); + } + verify_commitments_are_future(&replay, &previous_commitments)?; + replay.revision = commit.resulting_revision; + replay.state_digest = state_digest(&replay).map_err(kernel_error)?; + if replay.state_digest != commit.resulting_state_digest { + return Err(JournalError::Corrupt( + "commit resulting state digest is invalid".into(), + )); + } + replay.last_commit_digest = Some(commit.digest.clone()); + } + if &replay != state { + return Err(JournalError::Corrupt( + "head state does not equal replayed history".into(), + )); + } + Ok(()) +} + +/// The replay-side twin of `Mismatch::CommitmentDueInThePast`: every commitment +/// key this commit introduced is due after the post-commit clock. Replay already +/// reconstructs both sides, so this is a set difference over one partition. +fn verify_commitments_are_future( + state: &WorldState, + before: &BTreeMap>, +) -> Result<(), JournalError> { + for (subject_id, held) in &state.commitments { + for (key, commitment) in held { + let existed = before + .get(subject_id) + .is_some_and(|previous| previous.contains_key(key)); + if !existed && commitment.due <= state.now { + return Err(JournalError::Corrupt( + "a commitment was born at or after its own due date".into(), + )); + } + } + } + Ok(()) +} + +pub(super) fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> { + if state.schema != STATE_SCHEMA { + return Err(JournalError::Corrupt("invalid state schema".into())); + } + if state.title.trim().is_empty() || state.title.trim() != state.title { + return Err(JournalError::Corrupt( + "world title is empty or noncanonical".into(), + )); + } + if state.brief.trim() != state.brief { + return Err(JournalError::Corrupt("world brief is noncanonical".into())); + } + if state.brief.trim() != state.brief { + return Err(JournalError::Corrupt("world brief is noncanonical".into())); + } + super::validate_principal(&state.owner).map_err(kernel_error)?; + if state.subjects.is_empty() + || state.controller_assignments.len() != state.subjects.len() + || state.affordance_grants.is_empty() + { + return Err(JournalError::Corrupt( + "world ontology is empty or has split subject/controller ownership".into(), + )); + } + let is_place = |entity_id: &super::EntityId| { + state + .entities + .get(entity_id) + .is_some_and(|record| record.kind == super::EntityKind::Place) + }; + for (entity_id, entity) in &state.entities { + if !super::patch::is_canonical_text(&entity.label) { + return Err(JournalError::Corrupt( + "entity label is empty or noncanonical".into(), + )); + } + if let Some(container) = entity.container + && (entity.kind != super::EntityKind::Place || !is_place(&container)) + { + return Err(JournalError::Corrupt( + "entity container does not name a canonical place".into(), + )); + } + if !super::patch::containment_terminates(*entity_id, &state.entities) { + return Err(JournalError::Corrupt("place contains itself".into())); + } + } + for edge in state.edges.values() { + let (from, to) = edge.endpoints(); + if !is_place(&from) + || !is_place(&to) + || from == to + || !super::patch::is_valid_cost(edge.cost()) + { + return Err(JournalError::Corrupt( + "route does not join two distinct places at a valid cost".into(), + )); + } + } + for (subject_id, position) in &state.positions { + if !state.subjects.contains_key(subject_id) || !is_place(&position.place) { + return Err(JournalError::Corrupt( + "position does not name a canonical subject and place".into(), + )); + } + } + let is_resource = |entity_id: &super::EntityId| { + state + .entities + .get(entity_id) + .is_some_and(|record| record.kind == super::EntityKind::Resource) + }; + // Absence is zero and one slot holds one pair, so a store satisfying these + // clauses cannot carry a zero, an empty holder, a duplicate, or a dangling + // holding — with no scan for any of them. + for (subject_id, held) in &state.holdings { + if !state.subjects.contains_key(subject_id) + || held.is_empty() + || held + .iter() + .any(|(resource, quantity)| !is_resource(resource) || quantity.0 == 0) + { + return Err(JournalError::Corrupt( + "holding does not name a canonical subject and resource at a nonzero quantity" + .into(), + )); + } + } + for (subject_id, targets) in &state.dependencies { + let target_is_canonical = |target: &super::DependencyTarget| match target { + super::DependencyTarget::Resource(entity_id) => is_resource(entity_id), + super::DependencyTarget::Route(edge_id) => state.edges.contains_key(edge_id), + super::DependencyTarget::Subject(other) => { + other != subject_id && state.subjects.contains_key(other) + } + }; + if !state.subjects.contains_key(subject_id) + || targets.is_empty() + || !targets.iter().all(target_is_canonical) + { + return Err(JournalError::Corrupt( + "dependency does not name a canonical subject and a distinct canonical target" + .into(), + )); + } + } + // Facts, channels, and knowledge. The `facts`/`channels` bijections run both + // ways: a payload row without its entity, or an entity of that kind without + // its payload, is a referenceable half-thing. + for (entity_id, record) in &state.facts { + let standing_is_live = match &record.standing { + super::FactStanding::Canonical { evidence } => { + super::patch::is_canonical_text(evidence.text()) + } + super::FactStanding::Claimed { by } => state.subjects.contains_key(by), + super::FactStanding::Ruled => true, + }; + if !state + .entities + .get(entity_id) + .is_some_and(|entity| entity.kind == super::EntityKind::Fact) + || !super::patch::is_canonical_text(record.statement.as_str()) + || !standing_is_live + { + return Err(JournalError::Corrupt( + "a fact names no canonical entity, statement, or standing".into(), + )); + } + } + for (entity_id, record) in &state.channels { + let reach_is_live = match &record.reach { + super::Reach::Subjects(members) => members + .iter() + .all(|subject_id| state.subjects.contains_key(subject_id)), + super::Reach::Place(place) => is_place(place), + }; + if !state + .entities + .get(entity_id) + .is_some_and(|entity| entity.kind == super::EntityKind::Channel) + || !reach_is_live + || !record + .controller + .is_none_or(|subject_id| state.subjects.contains_key(&subject_id)) + { + return Err(JournalError::Corrupt( + "a channel names no canonical entity, reach, or controller".into(), + )); + } + } + for (entity_id, entity) in &state.entities { + let paired = match entity.kind { + super::EntityKind::Fact => state.facts.contains_key(entity_id), + super::EntityKind::Channel => state.channels.contains_key(entity_id), + super::EntityKind::Place | super::EntityKind::Resource => true, + }; + if !paired { + return Err(JournalError::Corrupt( + "a fact or channel entity carries no payload row".into(), + )); + } + } + for (subject_id, held) in &state.knowledge { + let entry_is_live = |entry: &super::Knowledge| { + entry.acquired_at <= state.revision + && match entry.source { + super::KnowledgeSource::Told { by, via } => { + state.subjects.contains_key(&by) + && via.is_none_or(|channel| state.channels.contains_key(&channel)) + } + super::KnowledgeSource::Seen { by } => state.subjects.contains_key(&by), + super::KnowledgeSource::Witnessed | super::KnowledgeSource::Evidenced => true, + } + }; + if !state.subjects.contains_key(subject_id) + || held.is_empty() + || held + .iter() + .any(|(fact, entry)| !state.facts.contains_key(fact) || !entry_is_live(entry)) + { + return Err(JournalError::Corrupt( + "knowledge does not name a canonical subject, fact, and source, or was acquired ahead of the world's revision" + .into(), + )); + } + } + // Commitments, pressures, attention stamps, and the authored scale target. + // Absence is the only spelling of nothing at every level, so a store + // satisfying these clauses carries no empty inner map, no zero magnitude, + // and no dangling row — with no scan for any of them. + for (subject_id, held) in &state.commitments { + let commitment_is_canonical = |commitment: &super::Commitment| { + (commitment.kind == super::CommitmentKind::Routine) == commitment.period.is_some() + && commitment.period.is_none_or(|period| { + (1..=super::patch::MAX_ROUTE_COST).contains(&period.minutes()) + }) + && (commitment.kind == super::CommitmentKind::Routine + || commitment.checks.is_empty()) + && match commitment.counterparty { + Some(counterparty) => { + counterparty != *subject_id + && state.subjects.contains_key(&counterparty) + && commitment.kind != super::CommitmentKind::Goal + } + None => true, + } + && commitment + .checks + .iter() + .all(|check| super::bound_precondition_is_live(state, check)) + }; + if !state.subjects.contains_key(subject_id) + || held.is_empty() + || !held.values().all(commitment_is_canonical) + { + return Err(JournalError::Corrupt( + "a commitment does not name a canonical promisor, counterparty, shape, or check" + .into(), + )); + } + } + for (target, held) in &state.pressures { + let source_is_live = |source: &super::PressureSource| match source { + super::PressureSource::Commitment { subject, key } => state + .commitments + .get(subject) + .is_some_and(|commitments| commitments.contains_key(key)), + super::PressureSource::Dependency(dependency) => state + .dependencies + .get(target) + .is_some_and(|targets| targets.contains(dependency)), + super::PressureSource::Subject(subject_id) => state.subjects.contains_key(subject_id), + }; + if !state.subjects.contains_key(target) + || held.is_empty() + || held + .iter() + .any(|(source, magnitude)| magnitude.0 == 0 || !source_is_live(source)) + { + return Err(JournalError::Corrupt( + "a pressure row does not name a canonical target, live source, and nonzero \ + magnitude" + .into(), + )); + } + } + if state + .last_opportunity_at + .iter() + .any(|(subject_id, stamp)| !state.subjects.contains_key(subject_id) || *stamp > state.now) + { + return Err(JournalError::Corrupt( + "an attention stamp names an unknown subject or a future minute".into(), + )); + } + if state + .scale_intent + .jurisdictions + .keys() + .any(|root| !is_place(root)) + || state + .scale_intent + .jurisdictions + .values() + .map(|weight| u64::from(*weight)) + .sum::() + > 1000 + { + return Err(JournalError::Corrupt( + "the scale intent names a non-place root or distributes more than the whole".into(), + )); + } + // The third statement of the draw rule, beside genesis and + // `SetLensWeights`: no stored world holds weights that never draw. + if !state.lens_weights.draws() { + return Err(JournalError::Corrupt("the lens weights never draw".into())); + } + // The civic subgraph, in the slot the deleted `authority_scope` check + // occupied: a jurisdiction names live ground under a canonical kind, an + // office sits on an institution and lends something to a person who holds + // no other office there, and a forum names a live subject. + let target_is_canonical = |target: &super::AuthorityTarget| match target { + super::AuthorityTarget::Subject(subject_id) => state.subjects.contains_key(subject_id), + super::AuthorityTarget::PlaceSubtree(entity_id) => is_place(entity_id), + }; + for (subject_id, grants) in &state.authority { + if !state.subjects.contains_key(subject_id) + || grants.is_empty() + || !grants.iter().all(|grant| { + super::patch::is_civic_name(&grant.kind.0) && target_is_canonical(&grant.over) + }) + { + return Err(JournalError::Corrupt( + "authority does not name a canonical subject and live ground under a canonical kind" + .into(), + )); + } + } + for (institution, offices) in &state.selection { + let mut incumbents = BTreeSet::new(); + if state.subjects.get(institution).map(|subject| subject.kind) + != Some(super::SubjectKind::Institution) + || offices.is_empty() + { + return Err(JournalError::Corrupt( + "an office register does not name a canonical institution".into(), + )); + } + for (name, office) in offices { + let incumbent_is_person = office.incumbent.is_none_or(|incumbent| { + state.subjects.get(&incumbent).map(|subject| subject.kind) + == Some(super::SubjectKind::Person) + && incumbents.insert(incumbent) + }); + if !super::patch::is_civic_name(&name.0) + || office.delegated.is_empty() + || !office + .delegated + .iter() + .all(|kind| super::patch::is_civic_name(&kind.0)) + || !incumbent_is_person + { + return Err(JournalError::Corrupt( + "an office lends nothing, is misnamed, or is held twice or by a non-person" + .into(), + )); + } + } + } + for (grievance, forum) in &state.redress { + if !super::patch::is_civic_name(&grievance.0) + || !state.subjects.contains_key(&forum.forum) + || !target_is_canonical(&forum.standing) + { + return Err(JournalError::Corrupt( + "a forum does not name a canonical grievance, subject, and standing".into(), + )); + } + } + if super::overlapping_holder(state).is_some() { + return Err(JournalError::Corrupt( + "one subject holds two overlapping jurisdictions of one kind".into(), + )); + } + let mut declared_keys = BTreeSet::new(); + let no_held = BTreeSet::new(); + for subject in state.subjects.values() { + if let Some(key) = &subject.import_key + && super::patch::import_key_fault(key, &no_held, &mut declared_keys).is_some() + { + return Err(JournalError::Corrupt( + "subject import key is malformed or held by two subjects".into(), + )); + } + } + let mut controller_ids = BTreeSet::new(); + for (subject_id, subject) in &state.subjects { + if !super::patch::is_canonical_text(&subject.label) { + return Err(JournalError::Corrupt( + "subject label is empty or noncanonical".into(), + )); + } + let scope = super::DecisionScope { + subject_id: *subject_id, + }; + let assignment = state + .controller_assignments + .get(&scope) + .ok_or_else(|| JournalError::Corrupt("decision subject has no controller".into()))?; + super::validate_assignment(assignment).map_err(kernel_error)?; + // A mirror has no controller id, so it joins no uniqueness set. + if let Some(controller_id) = assignment.id() + && !controller_ids.insert(controller_id) + { + return Err(JournalError::Corrupt( + "controller ID owns more than one canonical scope".into(), + )); + } + } + if state + .controller_assignments + .keys() + .any(|scope| !state.subjects.contains_key(&scope.subject_id)) + { + return Err(JournalError::Corrupt( + "controller assignment references an unknown subject".into(), + )); + } + for (scope, granted) in &state.affordance_grants { + if !state.controller_assignments.contains_key(scope) + || granted.is_empty() + || granted + .iter() + .any(|affordance_id| !state.affordance_catalog.contains_key(affordance_id)) + { + return Err(JournalError::Corrupt( + "affordance grant is empty, unscoped, or names no catalog entry".into(), + )); + } + } + // Both ways, the pairing `admit_resolved` decided: a mirror holds no grant, + // and every controller-bearing scope holds one. + if state + .controller_assignments + .iter() + .any(|(scope, assignment)| { + state.affordance_grants.contains_key(scope) != assignment.mode().is_some() + }) + { + return Err(JournalError::Corrupt( + "controller assignment and affordance grant do not pair".into(), + )); + } + // Every stored entry still passes the declaration validator, so a forged + // catalog row cannot install an entry the resolver would have refused. + for entry in state.affordance_catalog.values() { + if !super::patch::entry_is_admissible(entry) { + return Err(JournalError::Corrupt( + "stored affordance entry is not admissible".into(), + )); + } + } + // Approval shape holds only in Draft. Once the world is Active, the + // approvals that admitted it are frozen history: they are judged once by + // `reduce`'s `ActivateWorld` arm and after that by replay, not re-judged + // here against the present-day controller roster. Retiring the human + // (PA.f32) or adding a later human-controlled subject must not make a + // past activation retroactively corrupt. + if state.phase == super::WorldPhase::Draft { + let required = super::required_approvers(state); + if !state.draft_approvals.is_subset(&required) { + return Err(JournalError::Corrupt( + "draft approvals do not match canonical controller ownership".into(), + )); + } + } + let mut event_ids = BTreeSet::new(); + let mut claimed = BTreeSet::new(); + let mut previous_event_revision = 0; + for event in &state.events { + state + .controller_assignments + .get(&event.scope) + .ok_or_else(|| JournalError::Corrupt("event references an unknown scope".into()))?; + let entry = state + .affordance_catalog + .get(&event.affordance) + .ok_or_else(|| JournalError::Corrupt("event uses an unknown affordance".into()))?; + // A speech or display event names the claim it minted, and that claim + // is asserted by the acting subject and by no other event. + let mut minted_is_canonical = |fact: Option| { + fact.is_none_or(|fact| { + claimed.insert(fact) + && state.facts.get(&fact).is_some_and(|record| { + record.standing + == super::FactStanding::Claimed { + by: event.scope.subject_id, + } + }) + }) + }; + let speech_is_canonical = minted_is_canonical(event.speech); + let display_is_canonical = minted_is_canonical(event.display); + if !event_ids.insert(event.id) + || event.revision == 0 + || event.revision > state.revision + || event.revision <= previous_event_revision + // Present-tense controller identity and present-tense affordance + // grants are not judged here: retiring a subject or revoking a + // verb it once used must not corrupt the history of that use. + // Authority at commit time is judged once, by `reduce`, and after + // that by replay (`verify_history` re-runs `reduce` for every + // commit) and by the digest chain. This shape check only holds + // time-invariant facts: the event's scope resolves to a live + // assignment (checked above) and its affordance is a catalog + // entry (checked above). + || event.band >= entry.outcome_bands.len() + // Speech rides only a speech-carrying entry; such an entry always + // addresses someone, by words or by a visible act; a display may + // accompany any entry. + || (event.speech.is_some() && !entry.carries_speech) + || (entry.carries_speech && event.speech.is_none() && event.display.is_none()) + // One lowered operation per band effect, plus the two the speech + // lowering prepends and the two the display lowering adds. + || entry.outcome_bands[event.band].effects.len() + + if event.speech.is_some() { 2 } else { 0 } + + if event.display.is_some() { 2 } else { 0 } + != event.effects.len() + || !speech_is_canonical + || !display_is_canonical + { + return Err(JournalError::Corrupt( + "decision event is noncanonical or violates controller scope".into(), + )); + } + previous_event_revision = event.revision; + } + Ok(()) +} + +fn apply_committed_command( + state: &mut WorldState, + commit: &WorldCommit, +) -> Result<(), JournalError> { + let CommittedCommand::WorldCommand(command) = &commit.command else { + return Err(JournalError::Corrupt( + "creation command appears after world genesis".into(), + )); + }; + if command.world_id != state.world_id || command.expected_revision != state.revision { + return Err(JournalError::Corrupt( + "committed command does not target the exact replay state".into(), + )); + } + let expected_effect = reduce(state, command).map_err(kernel_error)?; + if expected_effect != commit.effect { + return Err(JournalError::Corrupt( + "committed effect is not the deterministic reduction of its command".into(), + )); + } + apply_effect( + state, + command.id, + &commit.command.caller(), + &expected_effect, + ) + .map_err(kernel_error) +} + +fn require_schema(row: &CultCacheEnvelope, schema: &str) -> Result<(), JournalError> { + if row.schema_id.as_deref() != Some(schema) { + Err(JournalError::Corrupt(format!( + "row {}/{} has the wrong schema", + row.r#type, row.key + ))) + } else { + Ok(()) + } +} + +fn envelope( + row_type: &str, + schema: &str, + key: String, + value: &T, +) -> Result { + Ok(CultCacheEnvelope { + key, + r#type: row_type.into(), + payload: rmp_serde::to_vec_named(value) + .map_err(|error| JournalError::Store(error.to_string()))?, + stored_at: Utc::now().to_rfc3339(), + schema_id: Some(schema.into()), + }) +} + +fn decode(row: &CultCacheEnvelope) -> Result { + let value: T = rmp_serde::from_slice(&row.payload).map_err(|error| { + JournalError::Corrupt(format!( + "could not decode row {}/{}: {error}", + row.r#type, row.key + )) + })?; + let canonical = rmp_serde::to_vec_named(&value) + .map_err(|error| JournalError::Corrupt(error.to_string()))?; + if canonical != row.payload { + return Err(JournalError::Corrupt(format!( + "row {}/{} is not canonical", + row.r#type, row.key + ))); + } + Ok(value) +} + +fn kernel_error(error: KernelError) -> JournalError { + JournalError::Corrupt(error.to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::WorldScaleIntentRef; + use crate::patch::kernel_speak_grant; + use crate::tests::speak_entry; + use crate::{ + AuthenticatedCaller, CallerId, CommandBody, CommandEnvelope, CreateWorld, Declaration, + DraftHandle, EntityDeclaration, EntityId, EntityKind, NewController, Position, PrincipalId, + Ref, SubjectDeclaration, SubjectKind, WorldKernel, WorldPatch, + }; + + #[derive(serde::Serialize, serde::Deserialize)] + struct CanonicalFixture { + value: u8, + } + + fn owner_patch(subject: SubjectDeclaration) -> WorldPatch { + WorldPatch { + declarations: vec![Declaration::Subject(subject)], + operations: Vec::new(), + evidence: Vec::new(), + } + } + + #[test] + fn decode_rejects_an_alternate_messagepack_shape() { + let row = CultCacheEnvelope { + key: "fixture".into(), + r#type: "fixture".into(), + payload: rmp_serde::to_vec(&CanonicalFixture { value: 7 }).unwrap(), + stored_at: Utc::now().to_rfc3339(), + schema_id: Some("fixture.v0".into()), + }; + assert!(decode::(&row).is_err()); + } + + #[test] + fn replay_rejects_a_forged_command_or_effect_even_with_valid_hashes() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let owner = PrincipalId::new("owner@example.test"); + let authenticated = AuthenticatedCaller::fixture(CallerId::Principal(owner.clone())); + let creation = CreateWorld { + lens_weights: crate::tests::stock_weights(), + id: CommandId::new(), + owner: owner.clone(), + title: "Before".into(), + brief: String::new(), + patch: owner_patch(SubjectDeclaration { + handle: DraftHandle::new("owner"), + label: "Owner".into(), + kind: SubjectKind::Person, + controller: NewController::Human { + principal: owner.clone(), + }, + affordances: kernel_speak_grant(), + position: None, + import_key: None, + }), + scale_intent: WorldScaleIntentRef::default(), + grammar: None, + }; + let (mut kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap(); + let snapshot = kernel.snapshot().unwrap(); + let command_id = CommandId::new(); + kernel + .submit( + CommandEnvelope { + id: command_id, + world_id: snapshot.world_id, + expected_revision: snapshot.revision, + caller: CallerId::Principal(owner), + body: CommandBody::ApproveDraft, + }, + &authenticated, + ) + .unwrap(); + + let mut command_forged_head = kernel.state.clone(); + let mut command_forged_commits = kernel.journal.commits.clone(); + let command_forged = command_forged_commits.get_mut(&command_id).unwrap(); + let CommittedCommand::WorldCommand(command) = &mut command_forged.command else { + panic!("expected a world command"); + }; + command.body = CommandBody::ActivateWorld; + command_forged.digest = commit_digest(command_forged).unwrap(); + command_forged_head.last_commit_digest = Some(command_forged.digest.clone()); + + assert!(matches!( + verify_history(&command_forged_head, &command_forged_commits), + Err(JournalError::Corrupt(_)) + )); + + let mut caller_forged_head = kernel.state.clone(); + let mut caller_forged_commits = kernel.journal.commits.clone(); + let caller_forged = caller_forged_commits.get_mut(&command_id).unwrap(); + let CommittedCommand::WorldCommand(command) = &mut caller_forged.command else { + panic!("expected a world command"); + }; + command.caller = CallerId::Principal(PrincipalId::new("attacker@example.test")); + caller_forged.digest = commit_digest(caller_forged).unwrap(); + caller_forged_head.last_commit_digest = Some(caller_forged.digest.clone()); + + assert!(matches!( + verify_history(&caller_forged_head, &caller_forged_commits), + Err(JournalError::Corrupt(_)) + )); + + let mut effect_forged_head = kernel.state.clone(); + let mut effect_forged_commits = kernel.journal.commits.clone(); + let effect_forged = effect_forged_commits.get_mut(&command_id).unwrap(); + effect_forged.effect = WorldEffect::WorldActivated; + effect_forged.digest = commit_digest(effect_forged).unwrap(); + effect_forged_head.last_commit_digest = Some(effect_forged.digest.clone()); + + assert!(matches!( + verify_history(&effect_forged_head, &effect_forged_commits), + Err(JournalError::Corrupt(_)) + )); + } + + #[test] + fn a_forged_patch_effect_does_not_apply() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let owner = PrincipalId::new("owner@example.test"); + let authenticated = AuthenticatedCaller::fixture(CallerId::Principal(owner.clone())); + let creation = CreateWorld { + lens_weights: crate::tests::stock_weights(), + id: CommandId::new(), + owner: owner.clone(), + title: "Kharad".into(), + brief: String::new(), + patch: owner_patch(SubjectDeclaration { + handle: DraftHandle::new("owner"), + label: "Owner".into(), + kind: SubjectKind::Person, + controller: NewController::Human { + principal: owner.clone(), + }, + affordances: kernel_speak_grant(), + position: None, + import_key: None, + }), + scale_intent: WorldScaleIntentRef::default(), + grammar: None, + }; + let (mut kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap(); + let snapshot = kernel.snapshot().unwrap(); + let command_id = CommandId::new(); + kernel + .submit( + CommandEnvelope { + id: command_id, + world_id: snapshot.world_id, + expected_revision: snapshot.revision, + caller: CallerId::Principal(owner), + body: CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("rhythm-road"), + label: "The Rhythm Road".into(), + kind: EntityKind::Place, + container: None, + }), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("rhythm-authority"), + label: "The Rhythm Authority".into(), + kind: SubjectKind::Institution, + controller: NewController::OperationalAgent, + affordances: BTreeSet::from([speak_entry(&kernel)]), + position: Some(Ref::Draft(DraftHandle::new("rhythm-road"))), + import_key: None, + }), + ], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + }, + &authenticated, + ) + .unwrap(); + + let mut forged_head = kernel.state.clone(); + let mut forged_commits = kernel.journal.commits.clone(); + let forged = forged_commits.get_mut(&command_id).unwrap(); + let WorldEffect::PatchAdmitted { resolved, .. } = &mut forged.effect else { + panic!("expected an admitted patch effect"); + }; + resolved.subjects[0].position = Some(Position { + place: EntityId::issue(), + }); + forged.digest = commit_digest(forged).unwrap(); + forged_head.last_commit_digest = Some(forged.digest.clone()); + + assert!(matches!( + verify_history(&forged_head, &forged_commits), + Err(JournalError::Corrupt(_)) + )); + } + + /// A store written at the schema this pass replaced is refused outright. + /// There is no migration adapter, and the refusal is the behaviour. + #[test] + fn a_store_from_the_knowledge_schema_is_refused() { + let row = CultCacheEnvelope { + key: "state".into(), + r#type: "world_state.knowledge.v1".into(), + payload: Vec::new(), + stored_at: Utc::now().to_rfc3339(), + schema_id: Some("ghostlight.world_state.knowledge.v1".into()), + }; + let error = recover(vec![row], None).unwrap_err(); + let JournalError::Corrupt(message) = error else { + panic!("expected a corrupt store"); + }; + assert!( + message.contains("unadmitted row type"), + "unexpected refusal: {message}" + ); + } + + /// A `Witness` reaches the store through two rows — a commit carries the + /// admitted operations and the state row carries the event's effects — so + /// both schemas bumped and both prior versions are refused at open. There + /// is no migration adapter and no dual read. + #[test] + fn a_store_written_before_the_witness_schema_is_refused() { + for (row_type, schema) in [ + (STATE_ROW, "ghostlight.world_state.consumer.v1"), + (COMMIT_ROW, "ghostlight.world_commit.consumer.v1"), + ] { + let row = CultCacheEnvelope { + key: "state".into(), + r#type: row_type.into(), + payload: Vec::new(), + stored_at: Utc::now().to_rfc3339(), + schema_id: Some(schema.into()), + }; + let error = recover(vec![row], None).unwrap_err(); + let JournalError::Corrupt(message) = error else { + panic!("expected a corrupt store for {schema}"); + }; + assert!( + message.contains("has the wrong schema"), + "unexpected refusal for {schema}: {message}" + ); + } + } + + /// Lens weights entered both rows — the state row holds them and a commit + /// row carries `LensWeightsReplaced` — so both schemas bumped and both + /// `consumer.v4` strings are refused at open. No migration, no dual read. + #[test] + fn a_store_written_before_the_lens_schema_is_refused() { + for (row_type, schema) in [ + (STATE_ROW, "ghostlight.world_state.consumer.v4"), + (COMMIT_ROW, "ghostlight.world_commit.consumer.v4"), + ] { + let row = CultCacheEnvelope { + key: "state".into(), + r#type: row_type.into(), + payload: Vec::new(), + stored_at: Utc::now().to_rfc3339(), + schema_id: Some(schema.into()), + }; + let error = recover(vec![row], None).unwrap_err(); + let JournalError::Corrupt(message) = error else { + panic!("expected a corrupt store for {schema}"); + }; + assert!( + message.contains("has the wrong schema"), + "unexpected refusal for {schema}: {message}" + ); + } + } + + /// A world whose history includes an owner's `SetLensWeights`, reopened + /// from its own store rows. + fn lens_history() -> (tempfile::TempDir, WorldKernel, crate::LensWeights) { + use crate::tests::{auth_principal, creation, owner, submit_owner}; + use crate::{Lens, LensWeights}; + + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, _) = WorldKernel::create( + directory.path().join("world.cc"), + creation(CommandId::new(), "Lens History"), + &auth_principal(owner()), + ) + .unwrap(); + let replaced = LensWeights::new(BTreeMap::from([ + (Lens::Patina, 0), + (Lens::Charter, 4), + (Lens::Ledger, 1), + (Lens::Numen, 2), + ])); + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + CommandBody::SetLensWeights { + weights: replaced.clone(), + }, + ); + (directory, kernel, replaced) + } + + fn rows_of(state: &WorldState, commits: &[WorldCommit]) -> Vec { + let mut rows: Vec = commits + .iter() + .map(|commit| { + envelope(COMMIT_ROW, COMMIT_SCHEMA, commit.command.id().key(), commit).unwrap() + }) + .collect(); + rows.push(envelope(STATE_ROW, STATE_SCHEMA, state.world_id.key(), state).unwrap()); + rows + } + + /// Replay re-derives the owner's weight change: the honest history reopens + /// to the same state digest and weights, and the store on disk does too. + #[test] + fn a_history_with_a_lens_weight_change_replays_exactly() { + let (directory, kernel, replaced) = lens_history(); + let honest: Vec = kernel.journal.commits.values().cloned().collect(); + let (_, replayed, commits) = + recover(rows_of(&kernel.state, &honest), None).expect("the honest history replays"); + assert_eq!(commits.len(), honest.len()); + assert_eq!(replayed.state_digest, kernel.state.state_digest); + assert_eq!(replayed.lens_weights, replaced); + + let (world_id, digest) = (kernel.state.world_id, kernel.state.state_digest.clone()); + drop(kernel); + let reopened = WorldKernel::open(directory.path().join("world.cc"), world_id).unwrap(); + assert_eq!(reopened.state.state_digest, digest); + assert_eq!(reopened.state.lens_weights, replaced); + } + + /// A stored weight change is not believed about who made it or what it + /// wrote. Each forgery re-seals the whole store around its rewrite: the + /// head state takes the effect's weights, its state digest is recomputed, + /// the commit's resulting state digest and its own digest follow, and the + /// head's last commit digest names the re-sealed commit. No digest can + /// answer for the check, which the drawing control proves: the same + /// re-sealing around a set that draws replays. + #[test] + fn a_forged_lens_weights_row_fails_replay() { + use crate::tests::human_principal; + use crate::{Lens, LensWeights}; + + let (_directory, kernel, _) = lens_history(); + let honest: Vec = kernel.journal.commits.values().cloned().collect(); + let forge = |rewrite: &dyn Fn(&mut WorldCommit)| -> (WorldState, Vec) { + let mut head = kernel.state.clone(); + let mut forged: Vec = honest.clone(); + let lens_row = forged + .iter_mut() + .filter(|commit| matches!(commit.effect, WorldEffect::LensWeightsReplaced { .. })) + .collect::>(); + let [commit] = <[&mut WorldCommit; 1]>::try_from(lens_row) + .expect("the history holds exactly one lens weights row"); + assert_eq!( + commit.resulting_revision, head.revision, + "the lens weights row is the head commit" + ); + rewrite(commit); + let WorldEffect::LensWeightsReplaced { weights } = &commit.effect else { + unreachable!("a lens weights row stays one"); + }; + head.lens_weights = weights.clone(); + head.state_digest = crate::state_digest(&head).unwrap(); + commit.resulting_state_digest = head.state_digest.clone(); + commit.digest = commit_digest(commit).unwrap(); + head.last_commit_digest = Some(commit.digest.clone()); + + // Every seal agrees with what it seals. + assert_eq!(crate::state_digest(&head).unwrap(), head.state_digest); + assert_eq!(commit_digest(commit).unwrap(), commit.digest); + assert_eq!(commit.resulting_state_digest, head.state_digest); + assert_eq!(head.last_commit_digest.as_deref(), Some(commit.digest.as_str())); + (head, forged) + }; + let set = |weights: LensWeights| { + move |commit: &mut WorldCommit| { + if let CommittedCommand::WorldCommand(command) = &mut commit.command { + command.body = CommandBody::SetLensWeights { + weights: weights.clone(), + }; + } + commit.effect = WorldEffect::LensWeightsReplaced { + weights: weights.clone(), + }; + } + }; + let refused = |(head, forged): (WorldState, Vec)| -> String { + let error = + recover(rows_of(&head, &forged), None).expect_err("a forged lens weights row replayed"); + let JournalError::Corrupt(detail) = error else { + panic!("unexpected refusal: {error:?}"); + }; + detail + }; + + // The control: a re-sealed store around a different set that draws + // replays, so the re-sealing leaves nothing for a digest to catch. + let drawing = LensWeights::new(BTreeMap::from([(Lens::Veil, 2), (Lens::Ember, 1)])); + let (head, forged) = forge(&set(drawing.clone())); + let (_, replayed, _) = + recover(rows_of(&head, &forged), None).expect("a consistent re-sealed store replays"); + assert_eq!(replayed.lens_weights, drawing); + + // A non-owner principal with a live approver role in this world. + let detail = refused(forge(&|commit| { + if let CommittedCommand::WorldCommand(command) = &mut commit.command { + command.caller = CallerId::Principal(human_principal()); + } + })); + assert!(detail.contains("Unauthorized") || detail.contains("does not own"), "{detail}"); + // The clock capability. + let detail = refused(forge(&|commit| { + if let CommittedCommand::WorldCommand(command) = &mut commit.command { + command.caller = CallerId::System(crate::SystemCapability::Clock); + } + })); + assert!(detail.contains("Unauthorized") || detail.contains("does not own"), "{detail}"); + // Every lens named, all at zero, in the command, its effect and the + // head: only the draw rule is left to refuse it. + let never = LensWeights::new(Lens::ALL.into_iter().map(|lens| (lens, 0)).collect()); + let detail = refused(forge(&set(never))); + assert!( + detail.contains("never draw") || detail.contains("LensWeightsNeverDraw"), + "something other than the draw rule refused the all-zero row: {detail}" + ); + } + + /// The third statement of the draw rule: a state row whose weights never + /// draw is refused by the shape check itself, not only by replay. + #[test] + fn a_state_row_whose_lens_weights_never_draw_is_refused() { + use crate::{Lens, LensWeights}; + + let (_directory, kernel, _) = lens_history(); + let mut forged = kernel.state.clone(); + forged.lens_weights = + LensWeights::new(Lens::ALL.into_iter().map(|lens| (lens, 0)).collect()); + let JournalError::Corrupt(detail) = + verify_state_shape(&forged).expect_err("an all-zero weight set passed the shape check") + else { + unreachable!("the shape check only reports corruption") + }; + assert!(detail.contains("lens weights"), "unexpected refusal: {detail}"); + + forged.lens_weights = LensWeights::default(); + assert!(verify_state_shape(&forged).is_err()); + assert!(verify_state_shape(&kernel.state).is_ok()); + + let commits: Vec = kernel.journal.commits.values().cloned().collect(); + let mut zeroed = kernel.state.clone(); + zeroed.lens_weights = + LensWeights::new(Lens::ALL.into_iter().map(|lens| (lens, 0)).collect()); + assert!(matches!( + recover(rows_of(&zeroed, &commits), None), + Err(JournalError::Corrupt(_)) + )); + } + + /// The tick is re-derived at replay by the same function that produced it, + /// so a committed motion rewritten after the fact no longer reduces from + /// its command. The clock chain refuses a rewritten reading the same way. + #[test] + fn a_forged_motion_does_not_replay() { + use crate::tests::{activate, auth_principal, command, owner}; + use crate::{ + AuthenticatedCaller, CallerId, CommandBody, FictionalMinutes, SystemCapability, + TickMinutes, + }; + + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let authenticated = auth_principal(owner()); + let (mut kernel, _) = WorldKernel::create( + &path, + crate::tests::creation(CommandId::new(), "Chronicle"), + &authenticated, + ) + .unwrap(); + let active = activate(&mut kernel); + let command_id = CommandId::new(); + let caller = CallerId::System(SystemCapability::Clock); + kernel + .submit( + command( + &active, + command_id, + caller.clone(), + CommandBody::AdvanceTime { + minutes: TickMinutes::new(30).unwrap(), + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .unwrap(); + + let mut forged_head = kernel.state.clone(); + let mut forged_commits = kernel.journal.commits.clone(); + let forged = forged_commits.get_mut(&command_id).unwrap(); + let WorldEffect::TimeAdvanced { to, .. } = &mut forged.effect else { + panic!("expected a time-advanced effect"); + }; + *to = FictionalMinutes(31); + forged.digest = commit_digest(forged).unwrap(); + forged_head.last_commit_digest = Some(forged.digest.clone()); + + assert!(matches!( + verify_history(&forged_head, &forged_commits), + Err(JournalError::Corrupt(_)) + )); + } + + /// Replay re-derives the operation half too: a committed relocation rewritten + /// to move a different subject no longer reduces from its command. + #[test] + fn a_forged_relocate_effect_does_not_apply() { + use crate::tests::{activate, admit_topology, auth_principal, command, owner}; + + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let authenticated = auth_principal(owner()); + let (mut kernel, _) = WorldKernel::create( + &path, + crate::tests::creation(CommandId::new(), "Kharad"), + &authenticated, + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + let active = activate(&mut kernel); + let command_id = CommandId::new(); + kernel + .submit( + command( + &active, + command_id, + CallerId::Principal(owner()), + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![crate::ComponentOp::Relocate { + subject: Ref::Existing(topology.walker), + via: Ref::Existing(topology.ramp), + }], + evidence: Vec::new(), + }, + }, + ), + &authenticated, + ) + .unwrap(); + + let mut forged_head = kernel.state.clone(); + let mut forged_commits = kernel.journal.commits.clone(); + let forged = forged_commits.get_mut(&command_id).unwrap(); + let WorldEffect::PatchAdmitted { resolved, .. } = &mut forged.effect else { + panic!("expected an admitted patch effect"); + }; + let crate::ResolvedOp::Relocate { subject_id, .. } = &mut resolved.operations[0] + else { + panic!("expected a lowered relocation"); + }; + *subject_id = crate::SubjectId::issue(); + forged.digest = commit_digest(forged).unwrap(); + forged_head.last_commit_digest = Some(forged.digest.clone()); + + assert!(matches!( + verify_history(&forged_head, &forged_commits), + Err(JournalError::Corrupt(_)) + )); + } + + /// Soul: `a_forged_band_or_forged_effect_does_not_apply` proves the live + /// `apply_effect` arm re-derives. `verify_state_shape` does not re-derive a + /// band — it only bounds the index and refuses effects under an empty band — + /// so the layer that kills a persisted forgery is replay effect-equality. + /// This forges a committed decision inside the journal, re-digests it into a + /// contiguous chain, and asserts recovery refuses it. + #[test] + fn soul_a_forged_band_or_effect_in_the_journal_dies_at_replay() { + use crate::tests::{ + activate, admit_custody, admit_topology, affordance_named, auth_principal, command, + opportunity_for, owner, + }; + use crate::{ + AuthenticatedCaller, DecisionInvocation, Magnitude, ProposedEffect, Quantity, + RoleBinding, Target, + }; + + let forge = |kind: &str, mutate: &dyn Fn(&mut crate::DecisionEvent)| { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let authenticated = auth_principal(owner()); + let (mut kernel, _) = WorldKernel::create( + &path, + crate::tests::creation(CommandId::new(), "ForgedDecision"), + &authenticated, + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + let custody = admit_custody(&mut kernel, &topology); + let active = activate(&mut kernel); + let entry = affordance_named(&active, kind); + let opportunity = opportunity_for(&active, custody.holder); + let caller = CallerId::Controller(opportunity.controller_id); + let command_id = CommandId::new(); + let role = |name: &str, target| RoleBinding { + role: crate::Role(name.into()), + target, + }; + kernel + .submit( + command( + &active, + command_id, + caller.clone(), + CommandBody::ExerciseDecision { + opportunity, + invocation: DecisionInvocation { + affordance: entry, + bindings: vec![ + role("from", Target::Subject(custody.holder)), + role("recipient", Target::Subject(custody.counterparty)), + role("place", Target::Entity(topology.yard)), + role("resource", Target::Entity(custody.tithe)), + ], + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::Quantity(Quantity(2)), + }], + speech: None, + display: None, + }, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .unwrap(); + + // The honest journal recovers. + assert!(verify_history(&kernel.state, &kernel.journal.commits).is_ok()); + + let mut forged_head = kernel.state.clone(); + let mut forged_commits = kernel.journal.commits.clone(); + let forged = forged_commits.get_mut(&command_id).unwrap(); + let WorldEffect::DecisionExercised { event, .. } = &mut forged.effect else { + panic!("expected an exercised decision effect"); + }; + mutate(event); + let forged_event = event.clone(); + *forged_head.events.last_mut().unwrap() = forged_event; + forged.digest = commit_digest(forged).unwrap(); + forged_head.last_commit_digest = Some(forged.digest.clone()); + forged_head.state_digest = String::new(); + forged_head.state_digest = crate::state_digest(&forged_head).unwrap(); + (forged_head, forged_commits) + }; + + // A band the seed did not draw, held inside a chain that verifies. + let (head, commits) = forge("carry_chance", &|event| { + event.band = (event.band + 1) % 3; + }); + assert!(matches!( + verify_history(&head, &commits), + Err(JournalError::Corrupt(_)) + )); + + // A magnitude the ceiling admitted but the lowering never produced. + let (head, commits) = forge("carry", &|event| { + let Some(crate::ResolvedOp::Transfer { qty, .. }) = event.effects.first_mut() + else { + panic!("expected a lowered transfer"); + }; + *qty = Quantity(1); + }); + assert!(matches!( + verify_history(&head, &commits), + Err(JournalError::Corrupt(_)) + )); + } + + #[test] + fn replay_rejects_genesis_that_does_not_derive_from_its_creation_command() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let owner = PrincipalId::new("owner@example.test"); + let authenticated = AuthenticatedCaller::fixture(CallerId::Principal(owner.clone())); + let creation_id = CommandId::new(); + let creation = CreateWorld { + lens_weights: crate::tests::stock_weights(), + id: creation_id, + owner: owner.clone(), + title: "Admitted".into(), + brief: String::new(), + patch: owner_patch(SubjectDeclaration { + handle: DraftHandle::new("owner"), + label: "Owner".into(), + kind: SubjectKind::Person, + controller: NewController::Human { principal: owner }, + affordances: kernel_speak_grant(), + position: None, + import_key: None, + }), + scale_intent: WorldScaleIntentRef::default(), + grammar: None, + }; + let (kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap(); + let mut forged_head = kernel.state.clone(); + let mut forged_commits = kernel.journal.commits.clone(); + let forged = forged_commits.get_mut(&creation_id).unwrap(); + let CommittedCommand::CreateWorld(command) = &mut forged.command else { + panic!("expected genesis creation command"); + }; + command.title = "Different command".into(); + forged.digest = commit_digest(forged).unwrap(); + forged_head.last_commit_digest = Some(forged.digest.clone()); + + assert!(matches!( + verify_history(&forged_head, &forged_commits), + Err(JournalError::Corrupt(_)) + )); + + let mut binding_forged_head = kernel.state.clone(); + let mut binding_forged_commits = kernel.journal.commits.clone(); + let binding_forged = binding_forged_commits.get_mut(&creation_id).unwrap(); + let WorldEffect::WorldCreated { resolved, .. } = &mut binding_forged.effect else { + panic!("expected genesis effect"); + }; + resolved.subjects[0].subject.label = "Not the creation subject".into(); + binding_forged.digest = commit_digest(binding_forged).unwrap(); + binding_forged_head.last_commit_digest = Some(binding_forged.digest.clone()); + + assert!(matches!( + verify_history(&binding_forged_head, &binding_forged_commits), + Err(JournalError::Corrupt(_)) + )); + } + + /// Soul falsification: the extended replay shape check is not decoration. + /// A forged store row carrying a self-loop, a cost out of range, a + /// non-place endpoint, or a position on a non-place is refused by + /// `recover`, which is the path `WorldJournal::open` takes. + #[test] + fn soul_forged_topology_store_rows_are_refused_on_recover() { + use crate::patch::{AccessKind, Cost, EdgeRecord, MAX_ROUTE_COST}; + use crate::tests::{admit_topology, auth_principal, owner}; + + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + crate::tests::creation(CommandId::new(), "Forged Rows"), + &auth_principal(owner()), + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + let commits: Vec = kernel + .journal + .commits + .values() + .map(|commit| { + envelope(COMMIT_ROW, COMMIT_SCHEMA, commit.command.id().key(), commit).unwrap() + }) + .collect(); + let rows_for = |state: &WorldState, row_type: &str| { + let mut rows = commits.clone(); + rows.push(envelope(row_type, STATE_SCHEMA, state.world_id.key(), state).unwrap()); + rows + }; + + // The honest state recovers. + assert!(recover(rows_for(&kernel.state, STATE_ROW), None).is_ok()); + + let self_loop = { + let mut state = kernel.state.clone(); + state.edges.insert( + topology.ramp, + EdgeRecord::Route { + label: "The Yard Ramp".into(), + from: topology.yard, + to: topology.yard, + access: AccessKind::Public, + cost: Cost(12), + open: true, + }, + ); + state + }; + let bad_cost = { + let mut state = kernel.state.clone(); + state + .edges + .get_mut(&topology.ramp) + .unwrap() + .set_cost(Cost(MAX_ROUTE_COST + 1)); + state + }; + let non_place_endpoint = { + let mut state = kernel.state.clone(); + state.entities.get_mut(&topology.road).unwrap().kind = + crate::EntityKind::Resource; + state + }; + let stray_position = { + let mut state = kernel.state.clone(); + state.positions.insert( + topology.walker, + Position { + place: EntityId::issue(), + }, + ); + state + }; + for forged in [self_loop, bad_cost, non_place_endpoint, stray_position] { + let error = recover(rows_for(&forged, STATE_ROW), None).unwrap_err(); + assert!( + matches!(error, JournalError::Corrupt(_)), + "a forged topology row recovered: {error:?}" + ); + } + } + + /// Soul falsification: a store written before the topology partitions is + /// refused outright, with no migration adapter in the path. + #[test] + fn soul_a_pre_topology_store_row_is_refused() { + use crate::tests::{admit_topology, auth_principal, owner}; + + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + crate::tests::creation(CommandId::new(), "Old Store"), + &auth_principal(owner()), + ) + .unwrap(); + admit_topology(&mut kernel); + let mut rows: Vec = kernel + .journal + .commits + .values() + .map(|commit| { + envelope( + "world_commit.foundation.v2", + COMMIT_SCHEMA, + commit.command.id().key(), + commit, + ) + .unwrap() + }) + .collect(); + rows.push( + envelope( + "world_state.foundation.v1", + STATE_SCHEMA, + kernel.state.world_id.key(), + &kernel.state, + ) + .unwrap(), + ); + let error = recover(rows, None).unwrap_err(); + let JournalError::Corrupt(message) = error else { + panic!("expected a corrupt store, got {error:?}"); + }; + assert!( + message.contains("unadmitted row type"), + "unexpected refusal: {message}" + ); + } + + /// A committed levy survives a restart exactly: the snapshot, the band, the + /// lowered effects, and the re-derived authority verdict all come back, and + /// the same envelope is already applied. + #[test] + fn restart_replay_after_a_levy_is_exact() { + use crate::tests::{affordance_named, civic_world, command, opportunity_for, owner}; + use crate::{ + DecisionInvocation, Magnitude, ProposedEffect, Quantity, Role, RoleBinding, + SubmitReceipt, Target, + }; + + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + crate::tests::creation(CommandId::new(), "Replayed Levy"), + &crate::tests::auth_principal(owner()), + ) + .unwrap(); + let (_, civic, active) = civic_world(&mut kernel); + let opportunity = opportunity_for(&active, civic.treasury); + let caller = CallerId::Controller(opportunity.controller_id); + let envelope = command( + &active, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + opportunity, + invocation: DecisionInvocation { + affordance: affordance_named(&active, "levy"), + bindings: vec![ + RoleBinding { + role: Role("payer".into()), + target: Target::Subject(civic.farmer), + }, + RoleBinding { + role: Role("resource".into()), + target: Target::Entity(civic.grain), + }, + ], + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::Quantity(Quantity(3)), + }], + speech: None, + display: None, + }, + }, + ); + kernel + .submit( + envelope.clone(), + &AuthenticatedCaller::fixture(caller.clone()), + ) + .unwrap(); + let committed = kernel.snapshot().unwrap(); + let event = kernel.state.events.last().expect("the levy event").clone(); + let world_id = committed.world_id; + drop(kernel); + + let mut reopened = WorldKernel::open(&path, world_id).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), committed); + let replayed = reopened.state.events.last().expect("the replayed event"); + assert_eq!(replayed.band, event.band); + assert_eq!(replayed.effects, event.effects); + assert!(matches!( + reopened + .submit(envelope, &AuthenticatedCaller::fixture(caller)) + .unwrap(), + SubmitReceipt::AlreadyApplied(_) + )); + } + + /// Soul falsification: the civic shape checks are not decoration. A forged + /// store row that widens a jurisdiction, doubles an incumbency, seats an + /// institution, or empties a delegation is refused by `recover`. + #[test] + fn a_forged_authority_or_incumbency_is_corrupt() { + use crate::tests::{ + BAILIFF_OFFICE, LEVY_KIND, WARDEN_OFFICE, auth_principal, authority_kind, civic_world, + office, owner, + }; + use crate::{AuthorityGrant, AuthorityTarget, Office}; + use std::collections::BTreeSet; + + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + crate::tests::creation(CommandId::new(), "Forged Civics"), + &auth_principal(owner()), + ) + .unwrap(); + let (topology, civic, _) = civic_world(&mut kernel); + let commits: Vec = kernel + .journal + .commits + .values() + .map(|commit| { + envelope(COMMIT_ROW, COMMIT_SCHEMA, commit.command.id().key(), commit).unwrap() + }) + .collect(); + let rows_for = |state: &WorldState| { + let mut rows = commits.clone(); + rows.push(envelope(STATE_ROW, STATE_SCHEMA, state.world_id.key(), state).unwrap()); + rows + }; + assert!(recover(rows_for(&kernel.state), None).is_ok()); + + let widened = { + let mut state = kernel.state.clone(); + state.authority.insert( + civic.reeve, + BTreeSet::from([AuthorityGrant { + kind: authority_kind(LEVY_KIND), + over: AuthorityTarget::PlaceSubtree(civic.chamber), + }]), + ); + state + }; + let dangling = { + let mut state = kernel.state.clone(); + state.authority.insert( + civic.outsider, + BTreeSet::from([AuthorityGrant { + kind: authority_kind(LEVY_KIND), + over: AuthorityTarget::PlaceSubtree(EntityId::issue()), + }]), + ); + state + }; + let doubled = { + let mut state = kernel.state.clone(); + state + .selection + .get_mut(&civic.treasury) + .unwrap() + .get_mut(&office(BAILIFF_OFFICE)) + .unwrap() + .incumbent = Some(civic.reeve); + state + }; + let seated_institution = { + let mut state = kernel.state.clone(); + state + .selection + .get_mut(&civic.treasury) + .unwrap() + .get_mut(&office(WARDEN_OFFICE)) + .unwrap() + .incumbent = Some(civic.treasury); + state + }; + let inert_office = { + let mut state = kernel.state.clone(); + state.selection.get_mut(&civic.treasury).unwrap().insert( + office(WARDEN_OFFICE), + Office { + incumbent: Some(civic.reeve), + delegated: BTreeSet::new(), + }, + ); + state + }; + let office_on_person = { + let mut state = kernel.state.clone(); + state + .selection + .insert(topology.walker, state.selection[&civic.treasury].clone()); + state + }; + for forged in [ + widened, + dangling, + doubled, + seated_institution, + inert_office, + office_on_person, + ] { + let error = recover(rows_for(&forged), None).unwrap_err(); + assert!( + matches!(error, JournalError::Corrupt(_)), + "a forged civic row recovered: {error:?}" + ); + } + } + + /// Soul falsification: a store written before the civic partitions is + /// refused outright, with no migration adapter in the path. + #[test] + fn a_store_from_the_previous_schema_is_refused() { + use crate::tests::{auth_principal, civic_world, owner}; + + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + crate::tests::creation(CommandId::new(), "Pre-Authority"), + &auth_principal(owner()), + ) + .unwrap(); + civic_world(&mut kernel); + let mut rows: Vec = kernel + .journal + .commits + .values() + .map(|commit| { + envelope( + "world_commit.affordance.v1", + COMMIT_SCHEMA, + commit.command.id().key(), + commit, + ) + .unwrap() + }) + .collect(); + rows.push( + envelope( + "world_state.affordance.v1", + STATE_SCHEMA, + kernel.state.world_id.key(), + &kernel.state, + ) + .unwrap(), + ); + let error = recover(rows, None).unwrap_err(); + let JournalError::Corrupt(message) = error else { + panic!("expected a corrupt store, got {error:?}"); + }; + assert!( + message.contains("unadmitted row type"), + "unexpected refusal: {message}" + ); + } + + /// Soul falsification of the structural-overlap decision, updated for the + /// admission-time covering check: a `Subject` grant naming ground a + /// `PlaceSubtree` grant already covers is refused on arrival, but nothing + /// re-derives that check off of live position. Once the farmer walks out + /// from under the hall, the identical grant is unremarkable, and no + /// `Relocate` — in either direction — is ever asked to keep a shape + /// decision current. + #[test] + fn a_relocation_never_corrupts_a_civic_store() { + use crate::tests::{ + LEVY_KIND, auth_principal, civic_world, operations, over_subject, owner, reject_owner, + submit_owner, + }; + use crate::{ComponentOp, Mismatch, SubmitReceipt}; + + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + crate::tests::creation(CommandId::new(), "Moving Civics"), + &auth_principal(owner()), + ) + .unwrap(); + let (_, civic, _) = civic_world(&mut kernel); + + let admit = |kernel: &mut WorldKernel, ops: Vec| { + let before = kernel.snapshot().unwrap(); + assert!(matches!( + submit_owner(kernel, &before, operations(ops)), + SubmitReceipt::Applied(_) + )); + verify_state_shape(&kernel.state).expect("the committed store keeps its shape"); + assert!( + crate::overlapping_holder(&kernel.state).is_none(), + "a committed store never holds two overlapping jurisdictions" + ); + }; + let place_covers = |kernel: &WorldKernel| { + crate::covers( + &kernel.state, + crate::AuthorityTarget::PlaceSubtree(civic.hall), + crate::Target::Subject(civic.farmer), + ) + }; + let name_farmer = || { + vec![crate::tests::grant_to( + civic.treasury, + LEVY_KIND, + over_subject(civic.farmer), + )] + }; + + // The treasury's hall grant already covers the farmer standing in the + // chamber underneath it, so naming him directly is a second source + // for the same kind of act, and admission refuses it while he stands + // there. + assert!(place_covers(&kernel)); + let before = kernel.snapshot().unwrap(); + assert_eq!( + reject_owner(&mut kernel, &before, operations(name_farmer())), + vec![Mismatch::OverlappingJurisdiction { operation: 0 }] + ); + + // Out of the subtree, one route at a time. + for edge in [civic.passage, civic.causeway] { + admit( + &mut kernel, + vec![ComponentOp::Relocate { + subject: Ref::Existing(civic.farmer), + via: Ref::Existing(edge), + }], + ); + } + // The move dissolved the cover without any operation naming it, which + // is why the disjointness rule cannot be occupancy-sensitive: nothing + // reruns the covering check on a `Relocate`, in or out. + assert!(!place_covers(&kernel)); + + // Now that he stands outside it, the identical grant is unremarkable. + admit(&mut kernel, name_farmer()); + assert!(kernel.state.authority[&civic.treasury].len() >= 3); + + // The whole history replays, and the reopened world is identical. + let committed = kernel.snapshot().unwrap(); + drop(kernel); + let reopened = WorldKernel::open(&path, committed.world_id).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), committed); + } +} + +#[cfg(test)] +mod custody_tests { + use super::*; + use crate::{ + CallerId, CommandBody, CommandId, ComponentOp, DependencyRef, EntityKind, Quantity, Ref, + SubmitReceipt, WorldKernel, WorldPatch, + tests::{admit_custody, admit_topology, auth_principal, command, creation, owner}, + }; + + /// Replay re-derives the custody partitions from the commit log alone: a + /// world reopened after a transfer is byte-identical, and the transfer's own + /// envelope is idempotent. + #[test] + fn restart_replay_after_a_transfer_is_exact() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let authenticated = auth_principal(owner()); + let (mut kernel, _) = + WorldKernel::create(&path, creation(CommandId::new(), "Replay"), &authenticated) + .unwrap(); + let topology = admit_topology(&mut kernel); + let custody = admit_custody(&mut kernel, &topology); + let active = crate::tests::activate(&mut kernel); + + let envelope = command( + &active, + CommandId::new(), + CallerId::Principal(owner()), + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Transfer { + from: Ref::Existing(custody.holder), + to: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(3), + }], + evidence: Vec::new(), + }, + }, + ); + let SubmitReceipt::Applied(receipt) = + kernel.submit(envelope.clone(), &authenticated).unwrap() + else { + panic!("expected an applied transfer"); + }; + let accepted = kernel.snapshot().unwrap(); + let world_id = accepted.world_id; + drop(kernel); + + let mut reopened = WorldKernel::open(&path, world_id).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), accepted); + assert_eq!( + reopened.submit(envelope, &authenticated).unwrap(), + SubmitReceipt::AlreadyApplied(receipt) + ); + } + + /// Replay recomputes `reduce`, so the band and the lowered operations are + /// re-derived rather than trusted: a stored event whose band or effects the + /// seed does not reproduce fails effect equality on the way back in. + #[test] + fn restart_replay_after_an_action_is_exact() { + use crate::tests::affordance_named; + use crate::{AuthenticatedCaller, Magnitude, ProposedEffect, RoleBinding, Target}; + + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let authenticated = auth_principal(owner()); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "ActionReplay"), + &authenticated, + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + let custody = admit_custody(&mut kernel, &topology); + let active = crate::tests::activate(&mut kernel); + let carry = affordance_named(&active, "carry"); + let opportunity = crate::tests::opportunity_for(&active, custody.holder); + let caller = CallerId::Controller(opportunity.controller_id); + + let role = |name: &str, target| RoleBinding { + role: crate::Role(name.into()), + target, + }; + let envelope = command( + &active, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + opportunity: opportunity.clone(), + invocation: crate::DecisionInvocation { + affordance: carry, + bindings: vec![ + role("from", Target::Subject(custody.holder)), + role("recipient", Target::Subject(custody.counterparty)), + role("place", Target::Entity(topology.yard)), + role("resource", Target::Entity(custody.tithe)), + ], + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::Quantity(Quantity(2)), + }], + speech: None, + display: None, + }, + }, + ); + let authenticated_controller = AuthenticatedCaller::fixture(caller); + let SubmitReceipt::Applied(receipt) = kernel + .submit(envelope.clone(), &authenticated_controller) + .unwrap() + else { + panic!("expected an applied invocation"); + }; + let accepted = kernel.snapshot().unwrap(); + let committed = kernel + .state + .events + .last() + .expect("the committed event") + .clone(); + assert!(!committed.effects.is_empty()); + let world_id = accepted.world_id; + drop(kernel); + + let mut reopened = WorldKernel::open(&path, world_id).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), accepted); + assert_eq!( + reopened.state.events.last().expect("the replayed event"), + &committed + ); + assert_eq!( + reopened + .submit(envelope, &authenticated_controller) + .unwrap(), + SubmitReceipt::AlreadyApplied(receipt) + ); + } + + /// A store written at the pass-2 schema is refused outright. There is no + /// migration adapter, and the refusal is the behaviour. + #[test] + fn a_store_from_the_previous_schema_is_refused() { + let row = CultCacheEnvelope { + key: "state".into(), + r#type: "world_state.topology.v1".into(), + payload: Vec::new(), + stored_at: Utc::now().to_rfc3339(), + schema_id: Some("ghostlight.world_state.topology.v1".into()), + }; + let error = recover(vec![row], None).unwrap_err(); + let JournalError::Corrupt(message) = error else { + panic!("expected a corrupt store"); + }; + assert!( + message.contains("unadmitted row type"), + "unexpected refusal: {message}" + ); + } + + /// PA.f39, M9: the Draft-only approval shape clause is defence in depth, + /// so it is pinned directly on `verify_state_shape` rather than only + /// through a full submit path. A fresh Draft world's approvals pass; a + /// forged principal outside `required_approvers` does not. + #[test] + fn draft_approvals_outside_required_approvers_is_corrupt() { + use crate::tests::{auth_principal, creation, owner}; + + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "PAf39ApprovalShape"), + &auth_principal(owner()), + ) + .unwrap(); + assert_eq!(kernel.state.phase, crate::WorldPhase::Draft); + verify_state_shape(&kernel.state) + .expect("a fresh Draft world has a canonical approval shape"); + + let mut forged = kernel.state.clone(); + forged + .draft_approvals + .insert(crate::PrincipalId::new("interloper@example.test")); + assert!( + matches!(verify_state_shape(&forged), Err(JournalError::Corrupt(_))), + "an approval outside the required set passed the shape check" + ); + } + + /// Absence is zero and one slot holds one pair, so a stored zero, an empty + /// holder, and a holding on something that is not a resource are each + /// corrupt at replay. + /// + /// Deviation from the spec's wording, decided here: the assertion is against + /// `verify_state_shape`, which owns these clauses. Routing through + /// `verify_history` would also fail on replay-equality, so it would pass + /// even if the shape clauses were deleted — which is the opposite of a + /// falsification. + #[test] + fn a_zero_or_dangling_holding_is_corrupt() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let authenticated = auth_principal(owner()); + let (mut kernel, _) = + WorldKernel::create(&path, creation(CommandId::new(), "Shape"), &authenticated) + .unwrap(); + let topology = admit_topology(&mut kernel); + let custody = admit_custody(&mut kernel, &topology); + crate::tests::activate(&mut kernel); + verify_state_shape(&kernel.state).expect("the admitted world has a canonical shape"); + + let mut zero = kernel.state.clone(); + zero.holdings + .get_mut(&custody.holder) + .unwrap() + .insert(custody.tithe, Quantity(0)); + assert!(matches!( + verify_state_shape(&zero), + Err(JournalError::Corrupt(_)) + )); + + let mut emptied = kernel.state.clone(); + emptied.holdings.get_mut(&custody.holder).unwrap().clear(); + assert!(matches!( + verify_state_shape(&emptied), + Err(JournalError::Corrupt(_)) + )); + + let mut not_a_resource = kernel.state.clone(); + assert_eq!( + not_a_resource.entities[&topology.yard].kind, + EntityKind::Place + ); + not_a_resource + .holdings + .get_mut(&custody.holder) + .unwrap() + .insert(topology.yard, Quantity(1)); + assert!(matches!( + verify_state_shape(¬_a_resource), + Err(JournalError::Corrupt(_)) + )); + + let mut dangling = kernel.state.clone(); + dangling.dependencies.insert( + custody.holder, + BTreeSet::from([crate::DependencyTarget::Subject(custody.holder)]), + ); + assert!(matches!( + verify_state_shape(&dangling), + Err(JournalError::Corrupt(_)) + )); + } + + /// Soul: replay is exact after *every* custody and dependency operation, not + /// only after a transfer. The reopened world is byte-identical, the last + /// envelope is idempotent, and the whole chain still verifies. + #[test] + fn soul_replay_is_exact_after_every_custody_operation() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let authenticated = auth_principal(owner()); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "EveryOperation"), + &authenticated, + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + // `Admit` and its evidence are Draft-only, so the opening balance is + // already on the log before activation. + let custody = admit_custody(&mut kernel, &topology); + let active = crate::tests::activate(&mut kernel); + + let envelope = command( + &active, + CommandId::new(), + CallerId::Principal(owner()), + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ + ComponentOp::Transfer { + from: Ref::Existing(custody.holder), + to: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(3), + }, + ComponentOp::Transform { + holder: Ref::Existing(custody.holder), + from_resource: Ref::Existing(custody.tithe), + into_resource: Ref::Existing(custody.ingot), + qty: Quantity(2), + }, + ComponentOp::Consume { + holder: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(1), + }, + ComponentOp::Bind { + subject: Ref::Existing(custody.holder), + target: DependencyRef::Route(Ref::Existing(topology.shutter)), + }, + ComponentOp::Bind { + subject: Ref::Existing(custody.holder), + target: DependencyRef::Subject(Ref::Existing(custody.counterparty)), + }, + ], + evidence: Vec::new(), + }, + }, + ); + let SubmitReceipt::Applied(receipt) = + kernel.submit(envelope.clone(), &authenticated).unwrap() + else { + panic!("expected an applied custody patch"); + }; + let accepted = kernel.snapshot().unwrap(); + let holdings = kernel.state.holdings.clone(); + let dependencies = kernel.state.dependencies.clone(); + let digest = kernel.state.state_digest.clone(); + let world_id = accepted.world_id; + drop(kernel); + + let mut reopened = WorldKernel::open(&path, world_id).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), accepted); + assert_eq!(reopened.state.holdings, holdings); + assert_eq!(reopened.state.dependencies, dependencies); + assert_eq!(reopened.state.state_digest, digest); + assert_eq!( + reopened.submit(envelope, &authenticated).unwrap(), + SubmitReceipt::AlreadyApplied(receipt) + ); + } + + /// Soul: a dependency naming a target of the wrong kind, or no canonical + /// target at all, is refused at replay. The shape clauses carry the + /// referential integrity the operation arm enforces at admission. + #[test] + fn soul_a_dependency_on_an_absent_or_wrong_kind_target_is_corrupt() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let authenticated = auth_principal(owner()); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "DependencyShape"), + &authenticated, + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + let custody = admit_custody(&mut kernel, &topology); + crate::tests::activate(&mut kernel); + verify_state_shape(&kernel.state).expect("the admitted world has a canonical shape"); + + // A place is not a resource, so a resource dependency naming one dangles. + let mut wrong_kind = kernel.state.clone(); + wrong_kind.dependencies.insert( + custody.holder, + BTreeSet::from([crate::DependencyTarget::Resource(topology.yard)]), + ); + assert!(matches!( + verify_state_shape(&wrong_kind), + Err(JournalError::Corrupt(_)) + )); + + // An empty target set is the second representation of nothing, and there + // is only supposed to be one. + let mut emptied = kernel.state.clone(); + emptied.dependencies.insert(custody.holder, BTreeSet::new()); + assert!(matches!( + verify_state_shape(&emptied), + Err(JournalError::Corrupt(_)) + )); + + // A holder key that names no canonical subject. + let mut orphan = kernel.state.clone(); + let absent = *orphan.subjects.keys().next().unwrap(); + orphan.dependencies.insert( + absent, + BTreeSet::from([crate::DependencyTarget::Resource(custody.tithe)]), + ); + orphan.subjects.remove(&absent); + assert!(matches!( + verify_state_shape(&orphan), + Err(JournalError::Corrupt(_)) + )); + } + + /// A world with one routine, one past-due goal, and a commit chain that + /// reaches them: the fixture the two clock-forgery checks below need. + fn ticking_world(path: &std::path::Path) -> (WorldKernel, super::super::SubjectId, CommandId) { + use crate::tests::{activate, auth_principal, command, operations, owner}; + use crate::{ + AuthenticatedCaller, CallerId, CommandBody, CommitmentKind, ComponentOp, + FictionalMinutes, Ref, SystemCapability, TickMinutes, + }; + + let authenticated = auth_principal(owner()); + let (mut kernel, _) = WorldKernel::create( + path, + crate::tests::creation(CommandId::new(), "Ticking"), + &authenticated, + ) + .unwrap(); + let active = activate(&mut kernel); + let subject = active.subjects.first().expect("a seeded subject").id; + let snapshot = kernel.snapshot().unwrap(); + kernel + .submit( + command( + &snapshot, + CommandId::new(), + CallerId::Principal(owner()), + operations(vec![ + ComponentOp::CreateCommitment { + subject: Ref::Existing(subject), + counterparty: None, + kind: CommitmentKind::Routine, + due: FictionalMinutes(10), + period: Some(TickMinutes::new(10).unwrap()), + checks: Vec::new(), + statement: crate::Statement::new("What was promised, as the promisor would say it.").unwrap(), + }, + ComponentOp::CreateCommitment { + subject: Ref::Existing(subject), + counterparty: None, + kind: CommitmentKind::Goal, + due: FictionalMinutes(20), + period: None, + checks: Vec::new(), + statement: crate::Statement::new("What was promised, as the promisor would say it.").unwrap(), + }, + ]), + ), + &authenticated, + ) + .unwrap(); + + let tick_id = CommandId::new(); + let caller = CallerId::System(SystemCapability::Clock); + let snapshot = kernel.snapshot().unwrap(); + kernel + .submit( + command( + &snapshot, + tick_id, + caller.clone(), + CommandBody::AdvanceTime { + minutes: TickMinutes::new(30).unwrap(), + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .unwrap(); + (kernel, subject, tick_id) + } + + /// Soul falsification: the replay gate and the `apply_effect` gate are two + /// independent re-derivations. This one exercises the replay side over a + /// motion that actually moved commitments and pressure — a rewritten + /// magnitude, a rewritten roll, and a fabricated row each stop replaying. + #[test] + fn soul_a_forged_tick_motion_does_not_replay() { + use crate::{FictionalMinutes, PressureMagnitude, PressureSource}; + + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (kernel, subject, tick_id) = ticking_world(&path); + let WorldEffect::TimeAdvanced { motion, .. } = &kernel + .journal + .commits + .get(&tick_id) + .expect("the tick's commit") + .effect + else { + panic!("expected a time-advanced effect"); + }; + assert!(!motion.fulfilled.is_empty(), "the routine rolled"); + assert!(!motion.pressed.is_empty(), "the past-due goal pressed"); + + let forge = |rewrite: fn(&mut crate::Motion)| { + let mut forged_head = kernel.state.clone(); + let mut forged_commits = kernel.journal.commits.clone(); + let forged = forged_commits.get_mut(&tick_id).unwrap(); + let WorldEffect::TimeAdvanced { motion, .. } = &mut forged.effect else { + panic!("expected a time-advanced effect"); + }; + rewrite(motion); + forged.digest = commit_digest(forged).unwrap(); + forged_head.last_commit_digest = Some(forged.digest.clone()); + verify_history(&forged_head, &forged_commits) + }; + + let rewrites: [fn(&mut crate::Motion); 4] = [ + // A magnitude the tick never wrote. + |motion| motion.pressed[0].magnitude = PressureMagnitude(42), + // A roll to a date the period does not reach. + |motion| motion.fulfilled[0].next_due = FictionalMinutes(9_999), + // A row for a source nothing derived. + |motion| { + let mut row = motion.pressed[0].clone(); + row.source = PressureSource::Subject(row.target); + motion.pressed.push(row); + }, + // A fulfilment dropped on the floor. + |motion| motion.fulfilled.clear(), + ]; + for rewrite in rewrites { + assert!( + matches!(forge(rewrite), Err(JournalError::Corrupt(_))), + "a forged motion replayed" + ); + } + let _ = subject; + } + + /// `TickMinutes` is `#[serde(transparent)]`, so a hand-written store row + /// can carry a period of zero — a routine that re-arms on the same minute + /// forever — without ever passing through `TickMinutes::new`. The shape + /// check now enforces the same `1..=MAX_ROUTE_COST` span bound the + /// constructor enforces, so the forged row is refused directly. + #[test] + fn soul_a_zero_period_is_refused_by_the_shape_check() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (kernel, subject, _) = ticking_world(&path); + + // The forgery an in-crate caller cannot write: `TickMinutes::new` + // refuses zero, and the field is private, so the only door is serde. + assert!(crate::TickMinutes::new(0).is_none()); + let zero: crate::TickMinutes = + rmp_serde::from_slice(&rmp_serde::to_vec(&0u32).unwrap()).expect("a transparent span"); + + let mut forged = kernel.state.clone(); + let key = *forged.commitments[&subject] + .iter() + .find(|(_, commitment)| commitment.period.is_some()) + .expect("the routine") + .0; + forged + .commitments + .get_mut(&subject) + .unwrap() + .get_mut(&key) + .unwrap() + .period = Some(zero); + + // The shape check refuses the forged span bound directly. + assert!( + matches!(verify_state_shape(&forged), Err(JournalError::Corrupt(_))), + "verify_state_shape admitted a period outside 1..=MAX_ROUTE_COST" + ); + + // The commit chain refuses it too. + let commits: Vec = kernel + .journal + .commits + .values() + .map(|commit| { + envelope(COMMIT_ROW, COMMIT_SCHEMA, commit.command.id().key(), commit).unwrap() + }) + .collect(); + let mut rows = commits; + rows.push(envelope(STATE_ROW, STATE_SCHEMA, forged.world_id.key(), &forged).unwrap()); + assert!(matches!(recover(rows, None), Err(JournalError::Corrupt(_)))); + } + + /// Replay re-decides authority, so a stored row is not believed about who + /// authored it. An honest elaborator commit is rewritten to claim a + /// jurisdiction that does not cover its answer, and the history it belongs + /// to stops recovering. + #[test] + fn soul_a_forged_elaborator_commit_row_fails_replay() { + use crate::tests::{activate, submit_owner}; + use crate::{ + AuthenticatedCaller, CausalBoundary, Declaration, DraftHandle, EntityDeclaration, + JurisdictionKey, PatchAnswer, RouteDeclaration, SystemCapability, + }; + + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "Forged Authorship"), + &auth_principal(owner()), + ) + .unwrap(); + let seed = kernel.snapshot().unwrap(); + let commons = seed.places[0].id; + submit_owner( + &mut kernel, + &seed, + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("road"), + label: "The Unwalked Road".into(), + kind: EntityKind::Place, + container: Some(Ref::Existing(commons)), + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("lane"), + label: "The Long Lane".into(), + from: Ref::Existing(commons), + to: Ref::Draft(DraftHandle::new("road")), + access: crate::AccessKind::Public, + cost: crate::Cost(1), + }), + ], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ); + activate(&mut kernel); + + let boundary = crate::derive_boundaries(&kernel.state) + .unwrap() + .into_iter() + .find(|boundary| matches!(boundary, CausalBoundary::UnelaboratedDestination { .. })) + .expect("the road is a dead end"); + let CausalBoundary::UnelaboratedDestination { place: road, .. } = boundary else { + unreachable!("the boundary was matched above") + }; + let caller = CallerId::System(SystemCapability::Elaborator { + jurisdiction: JurisdictionKey::PlaceSubtree(road), + }); + let snapshot = kernel.snapshot().unwrap(); + kernel + .submit( + command( + &snapshot, + CommandId::new(), + caller.clone(), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(boundary)), + patch: WorldPatch { + declarations: vec![Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("shed"), + label: "The Roadside Shed".into(), + kind: EntityKind::Place, + container: Some(Ref::Existing(road)), + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .expect("the honest elaboration commits"); + + let state_row = || { + envelope( + STATE_ROW, + STATE_SCHEMA, + kernel.state.world_id.key(), + &kernel.state, + ) + .unwrap() + }; + let rows_of = |commits: Vec| { + let mut rows: Vec = commits + .iter() + .map(|commit| { + envelope(COMMIT_ROW, COMMIT_SCHEMA, commit.command.id().key(), commit).unwrap() + }) + .collect(); + rows.push(state_row()); + rows + }; + + let honest: Vec = + kernel.journal.commits.values().cloned().collect(); + recover(rows_of(honest.clone()), None).expect("the honest history replays"); + + // Rewrite only the recorded caller, to a jurisdiction that does not + // cover the answer the same row carries. + let mut forged_one = false; + let forged: Vec = honest + .into_iter() + .map(|mut commit| { + if let crate::CommittedCommand::WorldCommand(command) = &mut commit.command + && matches!( + command.caller, + CallerId::System(SystemCapability::Elaborator { .. }) + ) + { + command.caller = CallerId::System(SystemCapability::Elaborator { + jurisdiction: JurisdictionKey::PlaceSubtree(commons), + }); + // Re-seal the row, so the chain digest cannot answer for + // the authority check. The elaborator commit is the last + // one, so no successor's `previous_commit_digest` moves. + commit.digest = commit_digest(&commit).unwrap(); + forged_one = true; + } + commit + }) + .collect(); + assert!(forged_one, "no elaborator row was found to forge"); + let error = recover(rows_of(forged), None).expect_err("a forged authorship replayed"); + let JournalError::Corrupt(detail) = &error else { + panic!("unexpected refusal: {error:?}"); + }; + assert!( + !detail.contains("commit chain is not contiguous"), + "the chain digest answered for the authority check: {detail}" + ); + } +} diff --git a/native/aetherlight/src/lens.rs b/native/aetherlight/src/lens.rs new file mode 100644 index 000000000..c14de9d8e --- /dev/null +++ b/native/aetherlight/src/lens.rs @@ -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); + +impl LensWeights { + pub fn new(weights: BTreeMap) -> 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 + '_ { + 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 { + // 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 { + (0..200) + .map(|i| CommandId::derived("l1-probe", &[&i.to_string()])) + .collect() + } + + fn tally(weights: &LensWeights) -> BTreeMap { + 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 = 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 = 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::(refused).is_err(), + "{refused} deserialized" + ); + } + let accepted = serde_json::from_str::(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 = 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""#, + ] + ); + } +} diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs new file mode 100644 index 000000000..3f64965c6 --- /dev/null +++ b/native/aetherlight/src/lib.rs @@ -0,0 +1,19173 @@ +//! The Ghostlight world library. +//! +//! The world owner is one deterministic authority: authenticated commands enter, +//! one reducer decides, and one journal atomically commits the resulting state. +//! Controllers may use models, but models never own lifecycle, scope, affordances, +//! opportunities, reduction, or persistence. +//! +//! A consumer reaches this crate through create/open, immutable snapshots, +//! command submission, typed receipts, and the runner and port entry points +//! below. The kernel itself is sealed: there is no mutable state, no canonical +//! ID allocator, no reducer entry, no journal writer, and no authenticated-caller +//! constructor on the public surface, under every configuration. This crate +//! declares no cargo features, so no build can lift the seal. +//! +//! The negative proofs are doc-tests, which compile as an external crate and so +//! stand exactly where a consumer stands. +//! +//! ```compile_fail,E0603 +//! use ghostlight::WorldKernel; +//! ``` +//! +//! ```compile_fail,E0603 +//! use ghostlight::reduce; +//! ``` +//! +//! ```compile_fail,E0603 +//! use ghostlight::WorldState; +//! ``` +//! +//! ```compile_fail,E0603 +//! use ghostlight::CommandEnvelope; +//! ``` +//! +//! ```compile_fail,E0603 +//! use ghostlight::AuthenticatedCaller; +//! ``` +//! +//! ```compile_fail,E0603 +//! use ghostlight::journal::WorldJournal; +//! ``` +//! +//! ```compile_fail,E0599 +//! let _ = ghostlight::SubjectId::issue(); +//! ``` +//! +//! ```compile_fail,E0603 +//! let _ = ghostlight::ScopeDigest::fixture("x"); +//! ``` +//! +//! ```compile_fail,E0425 +//! let _ = ghostlight::fixture_controller_opportunities(&[]); +//! ``` +//! +//! ```compile_fail,E0425 +//! let _ = ghostlight::fixture_inference_output("prose", "receipt"); +//! ``` + +mod action; +mod aetheria; +mod clock; +mod consumer; +mod controllers; +mod cover; +mod elaboration; +mod grammar; +#[cfg(test)] +mod import_key_tests; +mod journal; +mod lens; +mod local_inference; +mod mailbox; +mod patch; +mod sdk_inference; +mod table; +mod tool_schema; +mod vault; +mod verse; + +pub(crate) use action::ActionMismatch; +pub(crate) use clock::Motion; +pub use clock::{FictionalMinutes, TickMinutes}; +pub use consumer::{ + CONSUMER_BODY_LIMIT, CONSUMER_CREDENTIALS_ENVIRONMENT, CONSUMER_PATCH_SCHEMA, + CONSUMER_RECEIPT_SCHEMA, ConsumerRegistry, admit_document, encode_receipt, +}; +pub use controllers::{ + CONTROLLER_WORK_SCHEMA, CellRun, ConnectorBinding, ControllerError, ControllerModels, + ControllerOpenError, + ControllerNeed, ControllerPendingReason, ControllerRunner, ControllerWork, + ControllerWorkCustody, ControllerWorkLookup, ControllerWorkStore, ControllerWorkStoreError, + ControllerWorkWrite, + GroupedCheckpoint, InferenceEvent, InferenceFault, InferenceFaultClass, InferenceFaultDisposition, InferenceOutput, + InferencePort, + InferencePurpose, InferenceRequest, NarrativeCheckpoint, NarrativeRun, OperationalCheckpoint, + OperationalRun, PersonaLane, PreparedInference, SubmissionDisposition, TokenUsage, ToolResultOracle, + TracingInferencePort, open_controller_work, open_inference, +}; +pub(crate) use cover::{CellId, Constituent, Resolution}; +pub use aetheria::{ + AetheriaCatalog, AetheriaFaction, CatalogReadError, VerbRule, read_aetheria_catalog, +}; +pub use cover::{AgencyGraph, Cell, Cover, CoverBudget, CoverBudgetError, TickIndex, derive_cover}; +pub use elaboration::{ + ElaborationCheckpoint, ElaborationRunner, ElaboratorSession, EvidenceError, EvidenceQuery, + EvidenceReceipt, EvidenceSource, SeedCheckpoint, SeedOutcome, SeedRunner, select_row, +}; +pub use grammar::{ + GrammarBinding, GrammarError, GrammarIdentity, GrammarReferentKind, GrammarRole, GrammarVerb, + RenderPath, +}; +pub use lens::{Lens, LensWeights}; +pub use local_inference::{DEFAULT_HOSTED_MODEL_PREFIX, DEFAULT_LOCAL_MODEL_PREFIX, HostedBinding, LocalBinding}; +#[cfg(feature = "test-support")] +pub use local_inference::open_local_port_with_timeout; +pub(crate) use mailbox::ElaborationPort; +pub use mailbox::{ConsumerPort, ControllerPort, MailboxError, PlayPort, SeedPort, WorldMailbox}; +pub use patch::{ + CommitmentKey, DraftHandle, JurisdictionKey, Mismatch, PatchAnswer, Ref, RefKind, RefName, Role, + Site, Statement, WorldPatch, +}; +pub(crate) use patch::{ + AccessKind, Affordance, Audience, AuthoredSource, AuthorityGrant, AuthorityTarget, + BoundPrecondition, Bounds, ChannelRecord, Commitment, CommitmentKind, Confidence, Cost, + Declaration, DependencyTarget, EntityDeclaration, EntityKind, EvidenceRef, FactRecord, + FactStanding, Forum, GrievanceKindName, Knowledge, KnowledgeSource, Office, OfficeName, + PersonaMaterial, Position, PressureMagnitude, PressureSource, Quantity, Reach, + SubjectDeclaration, WorldScaleIntent, WorldScaleIntentRef, +}; +pub use patch::ImportKey; +#[cfg(test)] +use patch::{ + AffordanceDeclaration, AudienceRef, AudienceSpec, ChannelDeclaration, ComponentOp, + DependencyRef, FactDeclaration, FactStandingRef, ReachRef, RouteDeclaration, +}; +#[cfg(test)] +pub(crate) use patch::{ + AffordanceKindName, AuthorityGrantRef, AuthorityKindName, AuthorityTargetRef, ComponentOpKind, + EffectSlot, OutcomeBand, Precondition, RoleSpec, +}; +pub use sdk_inference::{DEFAULT_SDK_MODEL_PREFIX, SdkBinding}; +pub use table::{ + DecodedBatch, PatchSite, TableError, actor_tools, authoring_tools, decode_actor_call, + decode_authoring_call, decode_authoring_calls, describe_refusal, describe_refusal_to_actor, + id_text, id_text_matches, table_view, +}; +pub use vault::{VaultError, VaultEvidenceSource}; +pub use verse::{ + CALL_RECORD_SCHEMA, CallRecordError, CallRecordStore, CreateVerseWorldIntent, ProviderCallRecord, + RUN_RECORD_SCHEMA, RecordedCoverBudget, RecordingInferencePort, Refusal, RefusalReason, RunClaim, + ReplayInferencePort, RunField, RunId, RunOutcome, RunStart, RunStatus, TickCheckpoint, + TickReport, UnattributedCall, VerseGenesisError, VerseRunConfig, VerseRunError, VerseRunRecord, VerseRunStore, + call_run_id, run_manual, +}; +use patch::{EdgeRecord, EntityRecord, LedgerDelta, ResolvedOp, ResolvedPatch}; + +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::collections::{BTreeMap, BTreeSet}; +#[cfg(test)] +use std::path::Path; +use thiserror::Error; +use uuid::Uuid; + +/// Proof that the consumer verified a live principal, and the moment that +/// proof stops being worth anything. +/// +/// The consumer verifies; this library only bounds. `valid_until` is the +/// consumer's own session expiry, not a fresh clock read at construction, and +/// [`WorldMailbox::submit_principal`] refuses evidence presented after it — so +/// a long-lived holder such as [`SeedPort`] is bounded by the session that +/// vouched for it rather than by one request's lifetime. +/// +/// Keeping this type here, rather than taking the consumer's own session type, +/// is what keeps the consumer's principal format out of the kernel. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct VerifiedPrincipalEvidence { + account_subject_hash: String, + valid_until: DateTime, +} + +impl VerifiedPrincipalEvidence { + pub fn new(account_subject_hash: impl Into, valid_until: DateTime) -> Self { + Self { + account_subject_hash: account_subject_hash.into(), + valid_until, + } + } + + pub fn account_subject_hash(&self) -> &str { + &self.account_subject_hash + } + + pub fn valid_until(&self) -> DateTime { + self.valid_until + } + + #[cfg(test)] + pub(crate) fn fixture( + account_subject_hash: impl Into, + valid_until: DateTime, + ) -> Self { + Self::new(account_subject_hash, valid_until) + } +} + +pub const STATE_SCHEMA: &str = "ghostlight.world_state.consumer.v6"; +pub(crate) const COMMIT_SCHEMA: &str = "ghostlight.world_commit.consumer.v6"; + +/// Compatibility tag derived from [`STATE_SCHEMA`]: the trailing +/// `-` pair (e.g. `foundation-v1`). Callers that publish a +/// compatibility marker alongside the schema string must derive it from here +/// rather than hand-copying a second literal that can drift from the schema. +pub fn state_schema_compatibility_tag() -> String { + let mut segments = STATE_SCHEMA.rsplit('.'); + let version = segments.next().unwrap_or_default(); + let family = segments.next().unwrap_or_default(); + format!("{family}-{version}") +} + +/// The visibility argument is the whole boundary decision for an ID type: the +/// ones a consumer names by value are `pub`, the rest stay `pub(crate)`, and no +/// `issue()` impl is emitted here at all — issuance is private in every case. +macro_rules! opaque_uuid { + ($name:ident, $vis:vis) => { + #[derive( + Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, + )] + #[serde(transparent)] + $vis struct $name(Uuid); + }; + ($name:ident) => { + opaque_uuid!($name, pub(crate)); + }; +} + +opaque_uuid!(WorldId, pub); +opaque_uuid!(CommandId, pub); +opaque_uuid!(SubjectId, pub); +opaque_uuid!(EntityId, pub); +opaque_uuid!(EdgeId, pub); +opaque_uuid!(ControllerId); +opaque_uuid!(AffordanceId, pub); +opaque_uuid!(EventId); + +impl CommandId { + fn issue() -> Self { + Self(Uuid::new_v4()) + } + + pub fn new() -> Self { + Self::issue() + } + + pub fn parse_uuid(value: &str) -> Result { + Uuid::parse_str(value) + .map(Self) + .map_err(|_| KernelError::InvalidCommandId) + } + + /// The cell's own controller-work key. One row per cell per tick, derived so + /// a resumed tick reopens the row it wrote rather than starting a second + /// cognition chain over the same opportunities. + pub(crate) fn for_cell(world: WorldId, cell: cover::CellId, tick: cover::TickIndex) -> Self { + Self(cover::cell_work_uuid(world, cell, tick)) + } + + /// One constituent's submission id. Deterministic over + /// `(world, cell, subject, tick)`, so a resumed cell re-submits the same id + /// and the kernel's idempotency ledger answers with the original receipt + /// instead of committing a second time. + pub(crate) fn for_cell_constituent( + world: WorldId, + cell: cover::CellId, + subject: SubjectId, + tick: cover::TickIndex, + ) -> Self { + Self(cover::cell_constituent_uuid(world, cell, subject, tick)) + } + + /// sha256 over a namespace and its ordered, length-prefixed parts, first + /// sixteen bytes. A command key, not a referent id: `patch::derive_id` + /// still has exactly two call sites. No `uuid/v5`. + pub(crate) fn derived(namespace: &str, parts: &[&str]) -> Self { + let mut hasher = Sha256::new(); + hasher.update(namespace.as_bytes()); + for part in parts { + hasher.update((part.len() as u64).to_be_bytes()); + hasher.update(part.as_bytes()); + } + let bytes: [u8; 16] = hasher.finalize()[..16] + .try_into() + .expect("sha256 yields at least sixteen bytes"); + Self(Uuid::from_bytes(bytes)) + } + + fn key(self) -> String { + self.0.to_string() + } +} + +impl WorldId { + /// Canonical text, for the key derivations that hash a world identity. + pub(crate) fn text(self) -> String { + self.0.to_string() + } + + /// A named zero for tests that need a world identity and no world. + #[cfg(test)] + pub(crate) fn nil_for_test() -> Self { + Self(Uuid::nil()) + } + + fn issue() -> Self { + Self(Uuid::new_v4()) + } + + fn key(self) -> String { + self.0.to_string() + } +} + +// Subject, entity, controller, and affordance IDs are derived, never drawn. +// `patch::derive_id` is the only allocator, and it is called from exactly two +// sites: `patch::resolve_patch` and `action::exercise`. The action lane mints +// exactly one referent per invocation — always an `EntityKind::Fact`, always +// `Claimed` by the acting subject, never caller-named, never any other kind. +// These fixtures exist so tests can name an ID that no partition holds. +#[cfg(test)] +impl SubjectId { + fn issue() -> Self { + Self(Uuid::new_v4()) + } +} + +#[cfg(test)] +impl EntityId { + fn issue() -> Self { + Self(Uuid::new_v4()) + } +} + +#[cfg(test)] +impl ControllerId { + fn issue() -> Self { + Self(Uuid::new_v4()) + } +} + +#[cfg(test)] +impl AffordanceId { + fn issue() -> Self { + Self(Uuid::new_v4()) + } +} + +impl EventId { + fn for_command(command_id: CommandId) -> Self { + Self(command_id.0) + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub struct PrincipalId(String); + +impl PrincipalId { + pub fn new(value: impl Into) -> Self { + Self(value.into()) + } +} + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum WorldPhase { + Draft, + Active, +} + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub enum SubjectKind { + Person, + Institution, + Population, +} + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub enum ControllerMode { + Human, + NarrativePersona, + OperationalAgent, +} + +/// A configured external consumer. Opaque inside the kernel: derived from the +/// consumer's configured name at the ingress registry and never spelled back +/// out, so no consumer name can reach a match arm. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[serde(transparent)] +pub(crate) struct ConsumerId(Uuid); + +/// The one namespace a configured consumer name lowers through. +const CONSUMER_ID_NAMESPACE: &str = "ghostlight.consumer.id.v0"; + +impl ConsumerId { + /// The one lowering from a configured name, through `CommandId::derived`'s + /// recipe over its own namespace. Called only by the ingress registry. + pub(crate) fn of_name(name: &str) -> Self { + Self(CommandId::derived(CONSUMER_ID_NAMESPACE, &[name]).0) + } + + /// Canonical text, for the command-key derivation that hashes it. + pub(crate) fn text(self) -> String { + self.0.to_string() + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "type", rename_all = "snake_case")] +pub(crate) enum NewController { + Human { + principal: PrincipalId, + }, + NarrativePersona, + OperationalAgent, + /// Declared as a mirror of state this world does not own. Mints no + /// controller, no mode, and no opportunity. + External { + consumer: ConsumerId, + }, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +struct CreateWorld { + id: CommandId, + owner: PrincipalId, + title: String, + /// The world's authored premise, in the owner's words. Every lane reads it + /// as its guidance; nothing derives it and nothing writes it later. + brief: String, + patch: WorldPatch, + /// Authored once, here, and never mutated: `CommandBody::AdmitPatch` carries + /// no intent, so write-once is the command shape rather than a check. + scale_intent: WorldScaleIntentRef, + /// The world's flavor as genesis writes it. `SetLensWeights` may replace + /// it later; this command carries what the world began with. + lens_weights: LensWeights, + /// The grammar the world is bound to for its whole life, or none for an + /// open-catalog world. Authored here and nowhere else: genesis installs it. + #[serde(default, skip_serializing_if = "Option::is_none")] + grammar: Option, +} + +/// Unattributed creation intent. World ingress derives ownership, controller +/// identity, handles, kinds, and affordances from verified principal evidence. +#[derive(Clone, Debug)] +pub struct CreateWorldIntent { + pub id: CommandId, + pub title: String, + /// The premise, verbatim from the owner. May be empty: a world with no + /// brief is a deliberate choice, and its lanes then get no guidance. + pub brief: String, + pub human_subject_label: String, + pub narrative_persona_label: Option, + pub operational_agent_label: Option, + /// World-wide target of goal-bearing subjects per kind. Required, and may + /// be empty: a world with no target is a deliberate choice, not a default + /// that arrives because nobody said anything. + pub targets: BTreeMap, + /// The jurisdiction roots genesis declares beside the commons, because + /// `resolve_patch` only resolves roots the same patch declares. + pub jurisdictions: Vec, + /// Required. The library holds no default weights; a consumer states the + /// world's flavor or is refused. + pub lens_weights: LensWeights, +} + +/// One jurisdiction root as ingress states it. The handle is a string here and +/// a `DraftHandle` inside the world subtree, which is the one lowering: the +/// handle constructor is not reachable from runtime ingress. +#[derive(Clone, Debug)] +pub struct CreateJurisdictionIntent { + pub handle: String, + pub label: String, + pub permille: u32, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "type", content = "id", rename_all = "snake_case")] +enum CallerId { + Principal(PrincipalId), + Controller(ControllerId), + /// An internal capability. Never derived from session evidence, never + /// minted by ingress, and admitted for exactly one command body. + System(SystemCapability), +} + +/// Internally tagged, because a data-carrying variant cannot join a bare-string +/// encoding without silently changing every commit that already carries +/// `Clock`. The tag is part of the commit digest, so the schema bumps with it. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "capability", rename_all = "snake_case")] +enum SystemCapability { + Clock, + /// Authors structure inside one jurisdiction. Never derived from session + /// evidence, never minted by ingress, never held by a subject. + Elaborator { + jurisdiction: JurisdictionKey, + }, + /// One external consumer, authoring only the subjects this world has + /// admitted as its mirrors. Minted by exactly one mailbox method, after the + /// ingress has authenticated the document; never derived from session + /// evidence. + Consumer { + consumer: ConsumerId, + }, + /// The play table. Admitted for unanswered, unconfined Active patches, the + /// only author of `Ruled` facts and `Mint`, and for the clock. Minted only + /// by `PlayPort`. + Play, +} + +/// What a confined patch author may write. `None` from `require_patch_author` +/// still means unconfined: the owner. +/// +/// Deliberately not `AuthorityTarget`. That is in-world grant vocabulary read +/// by `covers` and `targets_overlap`; this names a caller's write scope, and +/// its consumer arm names a caller rather than a subject — the subject set is +/// derived from `controller_assignments` at decision time. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum PatchGround { + /// A place subtree. The elaborator's shape, unchanged in meaning. + Jurisdiction(JurisdictionKey), + /// Every subject bound to this consumer. + Consumer(ConsumerId), +} + +#[derive(Clone, Debug)] +struct AuthenticatedCaller { + caller: CallerId, +} + +impl AuthenticatedCaller { + fn verified_principal(principal: PrincipalId) -> Self { + Self { + caller: CallerId::Principal(principal), + } + } + + fn verified_controller(controller: ControllerId) -> Self { + Self { + caller: CallerId::Controller(controller), + } + } + + /// Visible only inside the `world` subtree and called only by + /// `WorldMailbox::submit_clock`. Runtime ingress cannot reach it. + fn verified_system(capability: SystemCapability) -> Self { + Self { + caller: CallerId::System(capability), + } + } + + #[cfg(test)] + fn fixture(caller: CallerId) -> Self { + Self { caller } + } +} + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(deny_unknown_fields)] +pub struct DecisionScope { + pub subject_id: SubjectId, +} + +/// The digest of exactly the components a proposal's verification reads: the +/// scope's controller assignment, its affordance grants, its subject's Position, +/// and the routes incident to that place. Built through the one `digest()` +/// helper over ordered containers, so it is a pure function of committed state. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub struct ScopeDigest(String); + +impl ScopeDigest { + fn as_str(&self) -> &str { + &self.0 + } + + #[cfg(test)] + pub(crate) fn fixture(value: &str) -> Self { + Self(value.into()) + } +} + +#[derive(Serialize)] +struct ScopePreimage<'a> { + world_id: WorldId, + subject_id: SubjectId, + controller: &'a ControllerAssignment, + /// The granted entries *and their definitions*: preconditions and ceilings + /// are what admission reads, so a change to a granted entry must change the + /// digest. + affordances: BTreeMap, + components: &'a ScopeComponents, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct DecisionOpportunity { + pub world_id: WorldId, + pub(crate) revision: u64, + pub(crate) scope_digest: ScopeDigest, + pub scope: DecisionScope, + pub(crate) controller_id: ControllerId, + pub controller_mode: ControllerMode, + pub affordance_ids: Vec, +} + +impl DecisionOpportunity { + pub(crate) fn digest(&self) -> Result { + digest(self) + } +} + +/// The referent a role is bound to. Canonical IDs only: an invocation happens +/// in Active, where no declaration exists, so a draft reference is +/// unrepresentable here and the action lane runs no draft resolution. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "target", content = "id", rename_all = "snake_case")] +pub(crate) enum Target { + Subject(SubjectId), + Entity(EntityId), + Edge(EdgeId), +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(deny_unknown_fields)] +pub struct RoleBinding { + pub(crate) role: Role, + pub(crate) target: Target, +} + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "magnitude", content = "value", rename_all = "snake_case")] +pub(crate) enum Magnitude { + None, + Quantity(Quantity), + Cost(Cost), +} + +/// One proposal against one effect slot. It carries no referents: they all come +/// from the slot's roles resolved through the invocation's bindings, so an +/// invocation cannot name a target its affordance declared no role for and the +/// ceiling check is a comparison rather than a graph walk. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct ProposedEffect { + pub(crate) slot: usize, + pub(crate) magnitude: Magnitude, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct DecisionInvocation { + pub affordance: AffordanceId, + pub bindings: Vec, + /// Exactly one entry per slot in the entry, in any order. + pub proposed: Vec, + /// Command input, and the only place an utterance's text enters the kernel. + /// The committed home of those bytes is `facts[fact].statement`. + pub speech: Option, + /// A visible act in the actor's own words, and the only place it enters + /// the kernel. It accompanies any invocation: a body is visible whatever + /// it is doing. Its audience is the actor's place, never the entry's. + pub display: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +struct CommandEnvelope { + id: CommandId, + world_id: WorldId, + expected_revision: u64, + caller: CallerId, + body: CommandBody, +} + +/// Unattributed human command intent. The mailbox derives the caller from +/// live app-session evidence before the reducer sees an envelope. +#[derive(Clone, Debug)] +pub struct PrincipalCommandIntent { + pub id: CommandId, + pub world_id: WorldId, + pub expected_revision: u64, + pub body: CommandBody, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum CommandBody { + ApproveDraft, + ActivateWorld, + ExerciseDecision { + opportunity: DecisionOpportunity, + invocation: DecisionInvocation, + }, + DeclineDecision { + opportunity: DecisionOpportunity, + }, + AdmitPatch { + /// Draft answers nothing. Active must answer a currently derived + /// boundary or a jurisdiction whose deficit is nonzero, and the commit + /// must satisfy what it answered. + answers: Option, + patch: WorldPatch, + }, + /// The world's only clock advance. Owner or the clock capability, and the + /// clock capability may do nothing else. + AdvanceTime { + minutes: TickMinutes, + }, + /// Replaces the world's whole lens weight set. Owner only, in any phase, + /// under genesis admission: a set that never draws is refused, and a zero + /// weight is admitted and never draws. A set that weighs every lens as + /// the current one does, however its map is spelled, changes nothing + /// canonical and is refused with `NoCanonicalChange` after admission, so + /// nothing commits. A session that already drew keeps its recorded lens. + SetLensWeights { + weights: LensWeights, + }, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +struct SubjectState { + label: String, + kind: SubjectKind, + /// Written only when a subject declaration is resolved; absent from a + /// subject nobody imported, so its digests are unchanged. + #[serde(default, skip_serializing_if = "Option::is_none")] + import_key: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "type", rename_all = "snake_case")] +enum ControllerAssignment { + Human { + controller_id: ControllerId, + principal: PrincipalId, + }, + NarrativePersona { + controller_id: ControllerId, + }, + OperationalAgent { + controller_id: ControllerId, + }, + /// A mirror of state this world does not own. It has no controller id and + /// no mode, because the kernel will not keep a fictional one so an accessor + /// can stay infallible. + ExternallyControlled { + consumer: ConsumerId, + }, + /// A subject `Retire` ended for good. Not a second partition: + /// `controller_assignments` stays the sole answer to who may call, and + /// this is one of its values. It has no controller id, no mode, and no + /// caller, so it mints no opportunity and is never an audience. + Retired, +} + +impl ControllerAssignment { + fn id(&self) -> Option { + match self { + Self::Human { controller_id, .. } + | Self::NarrativePersona { controller_id } + | Self::OperationalAgent { controller_id } => Some(*controller_id), + Self::ExternallyControlled { .. } | Self::Retired => None, + } + } + + fn mode(&self) -> Option { + match self { + Self::Human { .. } => Some(ControllerMode::Human), + Self::NarrativePersona { .. } => Some(ControllerMode::NarrativePersona), + Self::OperationalAgent { .. } => Some(ControllerMode::OperationalAgent), + Self::ExternallyControlled { .. } | Self::Retired => None, + } + } + + /// `None` for a retired subject: no caller may ever act for it again. A + /// mirror still returns `Some`, the one caller that could ever act for + /// its scope; the controller lane cannot mint it either, but that caller + /// exists and is comparable. + fn expected_caller(&self) -> Option { + match self { + Self::Human { principal, .. } => Some(CallerId::Principal(principal.clone())), + Self::NarrativePersona { controller_id } | Self::OperationalAgent { controller_id } => { + Some(CallerId::Controller(*controller_id)) + } + Self::ExternallyControlled { consumer } => Some(CallerId::System( + SystemCapability::Consumer { consumer: *consumer }, + )), + Self::Retired => None, + } + } + + fn consumer(&self) -> Option { + match self { + Self::ExternallyControlled { consumer } => Some(*consumer), + Self::Human { .. } + | Self::NarrativePersona { .. } + | Self::OperationalAgent { .. } + | Self::Retired => None, + } + } + + fn human_principal(&self) -> Option<&PrincipalId> { + match self { + Self::Human { principal, .. } => Some(principal), + Self::NarrativePersona { .. } + | Self::OperationalAgent { .. } + | Self::ExternallyControlled { .. } + | Self::Retired => None, + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(crate) struct DecisionEvent { + pub(crate) id: EventId, + pub(crate) revision: u64, + pub(crate) scope: DecisionScope, + pub(crate) controller_id: ControllerId, + /// The entry exercised. The invocation itself lives on the effect: the + /// invocation is what the caller said, the event is what the world recorded. + pub(crate) affordance: AffordanceId, + /// The claim this act asserted, if it carried speech. Never the text: the + /// event is the world's record and every reader reads it, so it carries the + /// fact id and the statement lives in `facts` alone. + pub(crate) speech: Option, + /// The claim this act displayed, if it carried a visible act. Same rule. + pub(crate) display: Option, + /// Index into the entry's `outcome_bands`. Re-derived and compared at apply + /// and at replay, never trusted. + pub(crate) band: usize, + /// The selected band's slots, lowered through the invocation's bindings. + /// Empty when the selected band names no effects. + pub(crate) effects: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +struct WorldState { + schema: String, + world_id: WorldId, + revision: u64, + phase: WorldPhase, + owner: PrincipalId, + title: String, + /// Authored at creation and never mutated; the one prose the world says + /// about itself, projected as guidance to every lane. + brief: String, + /// Bound by genesis and never written again; absent from a world with no + /// grammar, so such a world's state and digests are what they were before + /// grammars existed. + #[serde(default, skip_serializing_if = "Option::is_none")] + grammar: Option, + draft_approvals: BTreeSet, + subjects: BTreeMap, + entities: BTreeMap, + edges: BTreeMap, + positions: BTreeMap, + /// What each subject holds. Absence is zero at both levels: no stored + /// `Quantity(0)` and no empty inner map, so a duplicate holding is + /// unrepresentable and "nothing" has one shape. + holdings: BTreeMap>, + /// What each subject depends on. Never empty for a present key. + dependencies: BTreeMap>, + /// One row per `EntityKind::Fact` entity, and no orphan either way. Facts + /// are write-once: declaration and `AssertClaim` are the only writers, and + /// standing never changes after admission. + facts: BTreeMap, + /// One row per `EntityKind::Channel` entity, and no orphan either way. + channels: BTreeMap, + /// What each subject knows. The sole owner of who-heard-what: `events` + /// records what was done, and this decides what a subject may act on and + /// what its projection may contain. Never empty for a present key, and + /// absence is "knows nothing of it" — forgetting removes the key. + knowledge: BTreeMap>, + /// What ground each subject has jurisdiction over, and under which + /// world-declared kind. Never empty for a present key. No subject holds two + /// grants of one kind over overlapping ground, so nothing ever arbitrates + /// between two sources of one permission. + authority: BTreeMap>, + /// The offices each institution constitutes, and who sits in them. An + /// incumbent never exercises its institution's opportunity: + /// `controller_assignments` stays the sole answer to who may call, and an + /// office answers the different question of what its incumbent has + /// jurisdiction over. + selection: BTreeMap>, + /// Where each kind of grievance goes, and who may bring it. Keyed by + /// neither a subject nor a referent, so it enters no scope digest and is + /// admission-only state. + redress: BTreeMap, + /// What each subject has promised. Never empty for a present key. + commitments: BTreeMap>, + /// Lived meaning per subject. Read by projection and by nothing that + /// decides, so it enters `state_digest` and no `ScopePreimage`. + persona_material: BTreeMap, + /// Pressure *on* each subject, keyed target-major then source. Never empty + /// for a present key; no stored zero magnitude. + pressures: BTreeMap>, + /// When each subject was last given a decision opportunity it consumed. + /// Absence means never. The debt term of the attention order and nothing + /// else. + last_opportunity_at: BTreeMap, + /// Minutes since genesis. The world's only clock, advanced by exactly one + /// command body and read by no wall clock. It enters `state_digest` and no + /// `ScopePreimage`: it is world truth, and it is read by no precondition, so + /// a tick that only advances pressure moves no proposal's binding. + now: FictionalMinutes, + /// The authored scale target, written once by genesis and never mutated. + scale_intent: WorldScaleIntent, + /// Written by genesis and replaced only by `SetLensWeights`; read by the + /// elaborator's draw and by nothing that admits. It enters `state_digest` + /// and no `ScopePreimage`. + lens_weights: LensWeights, + controller_assignments: BTreeMap, + /// What an affordance *is*. World-authored, Draft-only, written by + /// `admit_resolved` alone. + affordance_catalog: BTreeMap, + /// Who may exercise which entry. A grant carries no payload, so a duplicate + /// grant is unrepresentable rather than checked. + affordance_grants: BTreeMap>, + events: Vec, + state_digest: String, + last_commit_digest: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "type", rename_all = "snake_case")] +enum WorldEffect { + WorldCreated { + owner: PrincipalId, + title: String, + brief: String, + resolved: ResolvedPatch, + }, + PatchAdmitted { + /// What this commit answered, so `apply_effect` re-decides the same + /// rule `reduce` decided and then proves the answer was satisfied. + answers: Option, + resolved: ResolvedPatch, + }, + DraftApproved { + principal: PrincipalId, + }, + WorldActivated, + DecisionExercised { + opportunity: DecisionOpportunity, + /// The command's own input, kept beside the event rather than inside it: + /// the invocation is what the caller said, the event is what the world + /// recorded, and only the first carries text. + invocation: DecisionInvocation, + event: DecisionEvent, + }, + DecisionDeclined { + opportunity: DecisionOpportunity, + }, + /// The first effect that mutates state for subjects other than one scope. + /// Its gate is the clock capability or the owner, and `apply_effect` + /// re-derives the whole motion, so a forged fulfilment, magnitude, row, or + /// target is one comparison rather than a clause apiece. + TimeAdvanced { + minutes: TickMinutes, + to: FictionalMinutes, + motion: Motion, + }, + /// The owner replaced the world's lens weights. `apply_effect` re-decides + /// the owner and the draw rule. + LensWeightsReplaced { + weights: LensWeights, + }, +} + +/// The exact raw command admitted by the world owner. This is the sole +/// persistent command authority: IDs, callers, retry identity, and effects are +/// derived from this value rather than copied into independently forgeable +/// commit fields. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "type", content = "command", rename_all = "snake_case")] +enum CommittedCommand { + CreateWorld(CreateWorld), + WorldCommand(CommandEnvelope), +} + +impl CommittedCommand { + fn id(&self) -> CommandId { + match self { + Self::CreateWorld(command) => command.id, + Self::WorldCommand(command) => command.id, + } + } + + fn caller(&self) -> CallerId { + match self { + Self::CreateWorld(command) => CallerId::Principal(command.owner.clone()), + Self::WorldCommand(command) => command.caller.clone(), + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +struct WorldCommit { + schema: String, + world_id: WorldId, + command: CommittedCommand, + previous_revision: Option, + resulting_revision: u64, + previous_state_digest: Option, + resulting_state_digest: String, + previous_commit_digest: Option, + effect: WorldEffect, + committed_at: DateTime, + digest: String, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SubjectSnapshot { + pub id: SubjectId, + pub label: String, + pub kind: SubjectKind, + /// The Aetheria record this subject was imported from, if it was. + pub import_key: Option, + /// Absent for an externally controlled mirror, which has no controller and + /// no turn. Every reader fails closed on `None`; none gets a default. + pub(crate) controller_id: Option, + pub controller_mode: Option, + pub human_controller: Option, + pub affordances: BTreeSet, + pub(crate) position: Option, + /// Set for a subject `Retire` ended: no opportunity, no position, no + /// audience, its history kept. The agent's view and the surface read this + /// rather than inferring retirement from an absent position, which a + /// merely unplaced live subject also has. + pub retired: bool, + /// Exactly what the scope digest binds for this subject, carried whole + /// rather than lowered into projections that then have to be diffed back + /// together: its own position, incident routes, holdings, dependencies, + /// grants, delegated offices, known fact keys, controlled channels, and + /// commitments. A counterparty's components never enter. The narrative lane + /// persists this as the "before" an interruption is measured against. + pub(crate) components: ScopeComponents, + pub(crate) offices_held: Vec, + /// View-only, and covered by no digest: an institution's own offices, so + /// its controller can see what it lends and to whom. No precondition reads + /// it, and installing a warden therefore does not reject the institution's + /// in-flight proposals — what an institution lends is not what it may do. + pub(crate) offices_granted: Vec, + /// View-only: the forums whose standing covers this subject, through the + /// same covering predicate `HasStanding` uses. + pub(crate) redress: Vec, + /// Every fact this subject holds, with the statement resolved. The sole + /// perception surface: a subject perceives a speech act if and only if it + /// holds `Knowledge` of that act's fact. Ordered by `minted_at` then `fact`. + pub(crate) knowledge: Vec, + /// Digest-bound, lowered from the one `scope_components` call `snapshot` + /// already makes, so view and digest cannot drift. Carries `past_due`, + /// which the components do not. + pub(crate) commitments: Vec, + /// Pressure on self. View-only: read by no precondition, so covered by no + /// digest. Pressure this subject *sources* is excluded — it is another + /// subject's state, and the actor already sees the commitment that produced + /// it. + pub(crate) pressures: Vec, + /// This subject's own dependencies, lowered from `components.dependencies` + /// (private to this module) so the play table's omniscient view can print + /// what a `release` may name without reaching into `ScopeComponents` + /// itself. View-only, covered by no digest of its own: it is already bound + /// through `components`. + pub(crate) dependencies: Vec, + /// What the subject carries as lived meaning, if anything was authored. + pub(crate) material: Option, + /// A projection of `qualifies`, not a stored flag and not a second count: + /// whether this subject already reduces its jurisdiction's scale deficit. + /// The seed brief needs to say which subjects count; recomputing the + /// conjunction outside the kernel would be a second definition of alive. + pub qualified: bool, + /// The greatest `DecisionEvent.revision` whose scope is this subject, or + /// `None` if the subject never acted. Derived from `state.events` alone: + /// no new state, no schema change. The recency marker `projector_knowledge` + /// stamps onto each knowledge row is `acquired_at > last_acted_at`. + pub(crate) last_acted_at: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct CommitmentSnapshot { + pub(crate) key: CommitmentKey, + pub(crate) kind: CommitmentKind, + pub(crate) counterparty: Option, + pub(crate) due: FictionalMinutes, + pub(crate) period: Option, + pub(crate) statement: Statement, + /// Derived in `snapshot` so a controller does not recompute it against a + /// clock it must be handed anyway. + pub(crate) past_due: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct PressureSnapshot { + pub(crate) source: PressureSource, + pub(crate) magnitude: PressureMagnitude, +} + +/// What a subject knows of one fact. `standing` carries no `EvidenceRef`: a +/// receipt is non-fictional provenance and never enters a subject-facing +/// surface, so a subject learns *that* a fact is canonical and never which +/// receipt admitted it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct KnowledgeSnapshot { + pub(crate) fact: EntityId, + pub(crate) statement: Statement, + pub(crate) standing: FactStandingView, + pub(crate) confidence: Confidence, + /// The speaker a subject sees is `Told { by }`. A subject holding a fact it + /// was never told sees the statement with no speaker, which is correct: it + /// knows the thing, not the telling. + pub(crate) source: KnowledgeSource, + /// The revision of the act that minted this claim, spoken or displayed, + /// when some committed event asserted it. + pub(crate) minted_at: Option, + /// The revision at which this subject acquired this row, from `Knowledge` + /// directly: always present, unlike `minted_at`, so the recency marker can + /// see a row a patch, a seed, or a ruling landed with no minting event. + pub(crate) acquired_at: u64, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum FactStandingView { + Canonical, + Claimed { by: SubjectId }, + /// Stated by the play table. Never produced for a subject-facing knowledge + /// row (`snapshot`'s per-subject projection still collapses it into + /// `Canonical`, because a subject's own perception cannot tell a ruled + /// fact from an ordinarily canonical one); produced only for the + /// omniscient `WorldSnapshot::facts` row the play table's own `table_view` + /// reads. + Ruled, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct OfficeSnapshot { + pub(crate) institution: SubjectId, + pub(crate) office: OfficeName, + pub(crate) incumbent: Option, + /// What the office actually lends: the institution's live grants whose kind + /// the office delegates. + pub(crate) authority: BTreeSet, +} + +/// A forum a subject may petition. It carries no standing: a subject learns +/// that it may bring a grievance, not the boundary of everyone else's standing. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct ForumSnapshot { + pub(crate) grievance: GrievanceKindName, + pub(crate) forum: SubjectId, +} + +/// One catalog entry as consumers read it. The whole entry, because every +/// derived surface — tool schemas, signature prose, the typed view's permission +/// block — is a projection of it and a narrower snapshot would be a second +/// vocabulary to keep in step. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub struct AffordanceSnapshot { + pub id: AffordanceId, + pub entry: Affordance, + /// Derived from the world's grammar by this entry's kind; none when the + /// world has no grammar. + pub render_path: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct ResourceSnapshot { + pub(crate) id: EntityId, + pub(crate) label: String, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PlaceSnapshot { + pub id: EntityId, + pub label: String, + pub(crate) container: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct RouteSnapshot { + pub(crate) id: EdgeId, + pub(crate) label: String, + pub(crate) from: EntityId, + pub(crate) to: EntityId, + pub(crate) access: AccessKind, + pub(crate) cost: Cost, + pub(crate) open: bool, +} + +/// A declared channel, standing rather than per-subject: `ChannelRecord` +/// carries no label (only `reach` and `controller`), so this is exactly that +/// record plus the canonical id, an omniscient row for the play table's own +/// view. No subject-facing surface reads it; a subject sees only the channels +/// it controls, through its own `components`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct ChannelSnapshot { + pub(crate) id: EntityId, + pub(crate) reach: Reach, + pub(crate) controller: Option, +} + +/// Every fact the world holds, canonical or not, with its real standing — +/// including `Ruled`, which every subject-facing knowledge row collapses to +/// `Canonical` — and who currently holds it. Built straight from +/// `state.facts` and `state.knowledge`, not from any subject's own knowledge +/// projection, so a fact nobody has been told or shown is still a row here: +/// `mint`, `transfer`, `witness`, and `acquire_knowledge` all take a fact id, +/// and the play table's omniscient view must be able to name one nobody +/// perceives yet. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct FactSnapshot { + pub(crate) id: EntityId, + pub(crate) statement: Statement, + pub(crate) standing: FactStandingView, + pub(crate) known_by: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct WorldSnapshot { + pub world_id: WorldId, + pub revision: u64, + pub phase: WorldPhase, + pub owner: PrincipalId, + pub title: String, + pub brief: String, + /// The bound grammar's identity; none for a world with an open catalog. + pub grammar: Option, + pub draft_approvals: BTreeSet, + pub required_approvers: BTreeSet, + pub subjects: Vec, + pub affordances: Vec, + pub places: Vec, + pub(crate) resources: Vec, + pub(crate) routes: Vec, + /// Every declared channel, omniscient: no subject-facing surface reads + /// this field. `communicate`'s audience may name one by id. + pub(crate) channels: Vec, + /// Every fact the world holds, omniscient and including facts nobody + /// currently perceives: no subject-facing surface reads this field, which + /// exists for the play table's own `table_view` alone. + pub(crate) facts: Vec, + /// Already ordered by pressure, then attention debt, then id: one owner, so + /// an operator interface, the mesh projection, and any future driver read + /// the same order and + /// none computes its own. + pub opportunities: Vec, + /// Everyone in a world shares the clock, and no controller can read a `due` + /// without it. + pub now: FictionalMinutes, + /// The elaborator's surface. There is no global pressure register and no + /// commitment gazetteer. + pub boundaries: Vec, + pub scale_deficit: Vec, + pub lens_weights: LensWeights, + pub state_digest: String, + pub last_commit_digest: Option, +} + +/// One committed act as the human operator's story feed reads it. It is the +/// operator surface, not a perception surface: no subject-facing lane receives +/// it, and `SelectedDecision` never sees an event log at all. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct OperatorEvent { + pub revision: u64, + pub speaker: SubjectId, + pub speaker_label: String, + pub speech: Option, + pub display: Option, + /// The affordance kind the act exercised. + pub verb: String, + /// How the world's grammar renders that verb; none in a world with no + /// grammar. + pub render_path: Option, + /// What the act bound each of the verb's roles to, in the invocation's + /// order. + pub roles: Vec, +} + +/// One role an act bound, with the label of what it was bound to. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct BoundRole { + pub role: String, + pub target: String, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CommitReceipt { + pub command_id: CommandId, + pub resulting_revision: u64, + pub resulting_state_digest: String, + pub commit_digest: String, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CreationReceipt { + pub command_id: CommandId, + pub world_id: WorldId, + pub resulting_state_digest: String, + pub commit_digest: String, +} + +impl CreationReceipt { + fn from_commit(commit: &WorldCommit) -> Result { + let CommittedCommand::CreateWorld(command) = &commit.command else { + return Err(KernelError::Invariant( + "world genesis receipt does not point to a creation command".into(), + )); + }; + let WorldEffect::WorldCreated { .. } = &commit.effect else { + return Err(KernelError::Invariant( + "world genesis receipt does not point to genesis".into(), + )); + }; + Ok(Self { + command_id: command.id, + world_id: commit.world_id, + resulting_state_digest: commit.resulting_state_digest.clone(), + commit_digest: commit.digest.clone(), + }) + } +} + +impl From<&WorldCommit> for CommitReceipt { + fn from(commit: &WorldCommit) -> Self { + Self { + command_id: commit.command.id(), + resulting_revision: commit.resulting_revision, + resulting_state_digest: commit.resulting_state_digest.clone(), + commit_digest: commit.digest.clone(), + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum SubmitReceipt { + Applied(CommitReceipt), + AlreadyApplied(CommitReceipt), +} + +#[derive(Debug, Error)] +pub enum KernelError { + #[error("command ID must be a UUID")] + InvalidCommandId, + #[error("world title must not be empty")] + EmptyTitle, + #[error("world owner or human controller principal must be canonical and nonempty")] + EmptyPrincipal, + #[error("patch rejected: {0:?}")] + PatchRejected(Vec), + #[error("action rejected: {0:?}")] + ActionRejected(Vec), + #[error("command targets another world")] + WorldMismatch, + #[error("authenticated caller does not match the command")] + AuthenticationMismatch, + #[error("caller does not own this world")] + Unauthorized, + #[error("command requires phase {expected:?}, current phase is {actual:?}")] + WrongPhase { + expected: WorldPhase, + actual: WorldPhase, + }, + #[error("caller is not a required draft approver")] + NotDraftApprover, + #[error("caller has already approved this draft")] + DraftAlreadyApproved, + #[error("draft is missing required approvals: {0:?}")] + MissingApprovals(Vec), + #[error("this world derives no such decision opportunity")] + OpportunityMismatch, + #[error("decision scope changed since the proposal was bound")] + ScopeChanged { + scope: DecisionScope, + expected: ScopeDigest, + actual: ScopeDigest, + }, + #[error("caller does not control this decision scope")] + ControllerMismatch, + #[error("decision affordance is not granted by the opportunity")] + AffordanceDenied, + #[error("expected revision {expected}, current revision {actual}")] + RevisionMismatch { expected: u64, actual: u64 }, + #[error("command ID was reused with different content")] + CommandIdConflict, + #[error("world creation ID was reused with different content")] + CreationConflict, + #[error("world creation target already contains another world")] + CreationTargetOccupied, + #[error("world has not been created")] + WorldNotCreated, + #[error("opened store contains another world")] + OpenedWorldMismatch, + #[error("world ownership is uncertain after command {command_id:?}; drop and reopen")] + RecoveryRequired { command_id: CommandId }, + #[error("world store path no longer names the owned database; drop and reopen explicitly")] + OwnershipLost, + #[error("canonical serialization failed: {0}")] + Serialization(String), + #[error("world store operation failed: {0}")] + Store(String), + #[error("world journal is corrupt: {0}")] + CorruptJournal(String), + #[error("private reducer invariant failed: {0}")] + Invariant(String), + #[error("an active patch must answer a derived boundary or a nonzero deficit")] + AnswerRequired, + #[error("this world derives no such boundary or deficit")] + AnswerNotDerived, + #[error("the admitted patch does not satisfy the boundary or deficit it answered")] + AnswerNotSatisfied, +} + +impl KernelError { + fn requires_owner_restart(&self) -> bool { + matches!( + self, + Self::RecoveryRequired { .. } + | Self::OwnershipLost + | Self::Store(_) + | Self::CorruptJournal(_) + | Self::Invariant(_) + ) + } +} + +impl From for KernelError { + fn from(error: journal::JournalError) -> Self { + match error { + journal::JournalError::WorldMismatch => Self::OpenedWorldMismatch, + journal::JournalError::RecoveryRequired { command_id } => { + Self::RecoveryRequired { command_id } + } + journal::JournalError::OwnershipLost => Self::OwnershipLost, + journal::JournalError::Store(detail) => Self::Store(detail), + journal::JournalError::Corrupt(detail) => Self::CorruptJournal(detail), + } + } +} + +struct WorldKernel { + state: WorldState, + journal: journal::WorldJournal, +} + +struct PreparedCreation { + command: CreateWorld, + world_id: WorldId, + owner: PrincipalId, + title: String, + brief: String, + resolved: ResolvedPatch, +} + +fn prepare_creation( + input: CreateWorld, + authenticated: &AuthenticatedCaller, +) -> Result { + let CallerId::Principal(authenticated_principal) = &authenticated.caller else { + return Err(KernelError::AuthenticationMismatch); + }; + validate_principal(&input.owner)?; + if &input.owner != authenticated_principal { + return Err(KernelError::AuthenticationMismatch); + } + let title = normalize_title(&input.title)?; + let brief = input.brief.trim().to_owned(); + // The world's own identity is not world structure, and it feeds every + // derived ID, so it is minted before resolution rather than by it. + let world_id = WorldId::issue(); + let resolved = patch::resolve_patch( + &WorldState::empty( + world_id, + input.owner.clone(), + title.clone(), + input.grammar.clone(), + ), + input.id, + &input.patch, + Some(&input.scale_intent), + Some(&input.lens_weights), + ) + .map_err(KernelError::PatchRejected)?; + require_ruler(&CallerId::Principal(input.owner.clone()), &resolved) + .map_err(KernelError::PatchRejected)?; + Ok(PreparedCreation { + world_id, + owner: input.owner.clone(), + title, + brief, + resolved, + command: input, + }) +} + +impl WorldKernel { + fn initialize( + empty: journal::EmptyWorldJournal, + prepared: PreparedCreation, + ) -> Result<(Self, CreationReceipt), KernelError> { + let world_id = prepared.world_id; + let effect = WorldEffect::WorldCreated { + owner: prepared.owner, + title: prepared.title, + brief: prepared.brief, + resolved: prepared.resolved, + }; + let mut state = WorldState::genesis(world_id, &prepared.command, &effect)?; + let mut genesis = WorldCommit { + schema: COMMIT_SCHEMA.into(), + world_id, + command: CommittedCommand::CreateWorld(prepared.command), + previous_revision: None, + resulting_revision: 0, + previous_state_digest: None, + resulting_state_digest: state.state_digest.clone(), + previous_commit_digest: None, + effect, + committed_at: Utc::now(), + digest: String::new(), + }; + genesis.digest = commit_digest(&genesis)?; + state.last_commit_digest = Some(genesis.digest.clone()); + let receipt = CreationReceipt::from_commit(&genesis)?; + let journal = empty.initialize(&state, &genesis)?; + Ok((Self { state, journal }, receipt)) + } + + fn retry_creation(&self, prepared: &PreparedCreation) -> Result { + self.journal.ensure_healthy()?; + let Some(commit) = self.journal.commit_for(prepared.command.id) else { + return Err(KernelError::CreationTargetOccupied); + }; + if commit.command != CommittedCommand::CreateWorld(prepared.command.clone()) + || !matches!(&commit.effect, WorldEffect::WorldCreated { .. }) + { + return Err(KernelError::CreationConflict); + } + CreationReceipt::from_commit(commit) + } + + #[cfg(test)] + fn create( + path: impl AsRef, + input: CreateWorld, + authenticated: &AuthenticatedCaller, + ) -> Result<(Self, CreationReceipt), KernelError> { + let prepared = prepare_creation(input, authenticated)?; + match journal::WorldJournal::open_owner(path.as_ref())? { + journal::JournalOpen::Empty(empty) => Self::initialize(empty, prepared), + journal::JournalOpen::Live { journal, state } => { + let kernel = Self { state, journal }; + let receipt = kernel.retry_creation(&prepared)?; + Ok((kernel, receipt)) + } + } + } + + #[cfg(test)] + fn open(path: impl AsRef, expected_world_id: WorldId) -> Result { + let (journal, state) = journal::WorldJournal::open(path.as_ref(), expected_world_id)?; + Ok(Self { state, journal }) + } + + fn snapshot(&self) -> Result { + self.journal.ensure_healthy()?; + snapshot(&self.state) + } + + /// The human operator's story feed. Separate from `snapshot` so that no + /// controller lane can reach an unscoped event log: a `WorldSnapshot` field + /// no consumer may read in full would be a loaded gun with a comment on it. + fn operator_log(&self) -> Result, KernelError> { + self.journal.ensure_healthy()?; + // An event records what the world did; the invocation, which names the + // bound roles, lives on the commit that produced it. + let invocations: BTreeMap = self + .journal + .commits() + .filter_map(|commit| match &commit.effect { + WorldEffect::DecisionExercised { + invocation, event, .. + } => Some((event.id, invocation)), + _ => None, + }) + .collect(); + operator_log(&self.state, &invocations) + } + + /// The tick driver's opportunity list, in the same order a snapshot + /// carries it. Separate from `snapshot` for the reason `agency_graph` is: + /// only the tick driver reads it. + fn opportunities(&self) -> Result, KernelError> { + self.journal.ensure_healthy()?; + Ok(order_opportunities( + &self.state, + derive_opportunities(&self.state)?, + )) + } + + /// How many clock advances the world has committed: the next tick's + /// ordinal, held by the world and read from its journal. Separate from + /// `snapshot` for the reason `opportunities` is: only the tick driver + /// reads it. + fn clock_advances(&self) -> Result { + self.journal.ensure_healthy()?; + Ok(self + .journal + .commits() + .filter(|commit| matches!(commit.effect, WorldEffect::TimeAdvanced { .. })) + .count() as u64) + } + + /// The scheduler's adjacency projection. Separate from `snapshot` for the + /// same reason `operator_log` is: it is wider than any subject view, so a + /// `WorldSnapshot` field carrying it would be reachable from every prompt + /// builder in the process. + fn agency_graph(&self) -> Result { + self.journal.ensure_healthy()?; + Ok(agency_graph(&self.state)) + } + + fn submit( + &mut self, + command: CommandEnvelope, + authenticated: &AuthenticatedCaller, + ) -> Result { + let committed_at = Utc::now(); + self.journal.ensure_healthy()?; + if command.world_id != self.state.world_id { + return Err(KernelError::WorldMismatch); + } + if command.caller != authenticated.caller { + return Err(KernelError::AuthenticationMismatch); + } + // Retry identity is caller plus body. The expected revision is stamped by + // the mailbox owner rather than supplied by the caller, so it is not part + // of what makes a command the same command. + if let Some(commit) = self.committed_command(command.id) { + let CommittedCommand::WorldCommand(committed) = &commit.command else { + return Err(KernelError::CommandIdConflict); + }; + return if committed.caller == command.caller && committed.body == command.body { + Ok(SubmitReceipt::AlreadyApplied(CommitReceipt::from(commit))) + } else { + Err(KernelError::CommandIdConflict) + }; + } + if command.expected_revision != self.state.revision { + return Err(KernelError::RevisionMismatch { + expected: command.expected_revision, + actual: self.state.revision, + }); + } + + let effect = reduce(&self.state, &command)?; + let mut candidate = self.state.clone(); + apply_effect(&mut candidate, command.id, &command.caller, &effect)?; + candidate.revision = candidate + .revision + .checked_add(1) + .ok_or_else(|| KernelError::Serialization("world revision overflow".into()))?; + candidate.state_digest = state_digest(&candidate)?; + + let mut commit = WorldCommit { + schema: COMMIT_SCHEMA.into(), + world_id: self.state.world_id, + command: CommittedCommand::WorldCommand(command), + previous_revision: Some(self.state.revision), + resulting_revision: candidate.revision, + previous_state_digest: Some(self.state.state_digest.clone()), + resulting_state_digest: candidate.state_digest.clone(), + previous_commit_digest: self.state.last_commit_digest.clone(), + effect, + committed_at, + digest: String::new(), + }; + commit.digest = commit_digest(&commit)?; + candidate.last_commit_digest = Some(commit.digest.clone()); + + self.journal.commit(&candidate, &commit)?; + self.state = candidate; + Ok(SubmitReceipt::Applied(CommitReceipt::from(&commit))) + } + + fn committed_command(&self, command_id: CommandId) -> Option<&WorldCommit> { + self.journal.commit_for(command_id) + } + + fn controller_receipt( + &self, + command_id: CommandId, + opportunity: &DecisionOpportunity, + invocation: &DecisionInvocation, + ) -> Result, KernelError> { + self.journal.ensure_healthy()?; + let Some(commit) = self.committed_command(command_id) else { + return Ok(None); + }; + let CommittedCommand::WorldCommand(CommandEnvelope { + body: + CommandBody::ExerciseDecision { + opportunity: committed_opportunity, + invocation: committed_invocation, + }, + .. + }) = &commit.command + else { + return Err(KernelError::CommandIdConflict); + }; + if committed_opportunity != opportunity || committed_invocation != invocation { + return Err(KernelError::CommandIdConflict); + } + Ok(Some(CommitReceipt::from(commit))) + } + + fn controller_decline_receipt( + &self, + command_id: CommandId, + opportunity: &DecisionOpportunity, + ) -> Result, KernelError> { + self.journal.ensure_healthy()?; + let Some(commit) = self.committed_command(command_id) else { + return Ok(None); + }; + let CommittedCommand::WorldCommand(CommandEnvelope { + body: + CommandBody::DeclineDecision { + opportunity: committed_opportunity, + }, + .. + }) = &commit.command + else { + return Err(KernelError::CommandIdConflict); + }; + if committed_opportunity != opportunity { + return Err(KernelError::CommandIdConflict); + } + Ok(Some(CommitReceipt::from(commit))) + } +} + +fn reduce(state: &WorldState, command: &CommandEnvelope) -> Result { + // The one admission rule for internal capabilities, stated here and again + // at the top of `apply_effect`: `reduce` decides and `apply_effect` + // re-decides, which is how every gate in this file is written. + require_system_capability(&command.caller, &command.body)?; + match &command.body { + CommandBody::ApproveDraft => { + require_phase(state, WorldPhase::Draft)?; + let CallerId::Principal(principal) = &command.caller else { + return Err(KernelError::NotDraftApprover); + }; + if !required_approvers(state).contains(principal) { + return Err(KernelError::NotDraftApprover); + } + if state.draft_approvals.contains(principal) { + return Err(KernelError::DraftAlreadyApproved); + } + Ok(WorldEffect::DraftApproved { + principal: principal.clone(), + }) + } + CommandBody::ActivateWorld => { + require_owner(state, &command.caller)?; + require_phase(state, WorldPhase::Draft)?; + let missing: Vec<_> = required_approvers(state) + .difference(&state.draft_approvals) + .cloned() + .collect(); + if !missing.is_empty() { + return Err(KernelError::MissingApprovals(missing)); + } + Ok(WorldEffect::WorldActivated) + } + CommandBody::ExerciseDecision { + opportunity, + invocation, + } => { + require_phase(state, WorldPhase::Active)?; + let current = exact_opportunity(state, opportunity)?; + let assignment = state + .controller_assignments + .get(¤t.scope) + .ok_or(KernelError::OpportunityMismatch)?; + if assignment.expected_caller().as_ref() != Some(&command.caller) { + return Err(KernelError::ControllerMismatch); + } + let granted = require_granted(state, ¤t, invocation.affordance)?; + let event = action::exercise(state, command.id, ¤t, &granted, invocation)?; + Ok(WorldEffect::DecisionExercised { + opportunity: current, + invocation: invocation.clone(), + event, + }) + } + CommandBody::DeclineDecision { opportunity } => { + require_phase(state, WorldPhase::Active)?; + let current = exact_opportunity(state, opportunity)?; + let assignment = state + .controller_assignments + .get(¤t.scope) + .ok_or(KernelError::OpportunityMismatch)?; + if assignment.expected_caller().as_ref() != Some(&command.caller) { + return Err(KernelError::ControllerMismatch); + } + Ok(WorldEffect::DecisionDeclined { + opportunity: current, + }) + } + CommandBody::AdvanceTime { minutes } => { + // There is no time in Draft: a world under construction has no due + // dates to cross. + require_phase(state, WorldPhase::Active)?; + require_clock_caller(state, &command.caller)?; + let to = state + .now + .checked_add(*minutes) + .ok_or_else(|| KernelError::Serialization("world clock overflow".into()))?; + // A tick with an empty motion is still a commit: the clock moved, + // which is a canonical change. That is why the clock is a state + // field rather than a patch operation. + Ok(WorldEffect::TimeAdvanced { + minutes: *minutes, + to, + motion: clock::derive_motion(state, to), + }) + } + CommandBody::AdmitPatch { answers, patch } => { + // Answer before authority, because the jurisdiction check reads the + // answer and a missing one must read as `AnswerRequired` rather + // than `Unauthorized`. Resolution before confinement, because + // confinement reads draft-resolved referents and a structurally + // broken patch should return its complete mismatch set rather than + // a jurisdiction complaint about a reference that does not resolve. + require_answer( + state, + &command.caller, + answers.as_ref(), + !(patch.declarations.is_empty() && patch.evidence.is_empty()), + )?; + let confinement = require_patch_author(state, &command.caller, answers.as_ref())?; + let resolved = patch::resolve_patch(state, command.id, patch, None, None) + .map_err(KernelError::PatchRejected)?; + require_ruler(&command.caller, &resolved).map_err(KernelError::PatchRejected)?; + if let Some(ground) = confinement { + confine_to_ground(state, &resolved, ground).map_err(KernelError::PatchRejected)?; + } + Ok(WorldEffect::PatchAdmitted { + answers: answers.clone(), + resolved, + }) + } + CommandBody::SetLensWeights { weights } => { + require_owner(state, &command.caller)?; + if !weights.draws() { + return Err(KernelError::PatchRejected(vec![ + Mismatch::LensWeightsNeverDraw, + ])); + } + // Admission first, then effect: a caller who may not set weights, + // or a set that never draws, is refused as such even when it + // equals the current set. Only an admitted set can be a no-op. + if weights.weighs_the_same_as(&state.lens_weights) { + return Err(KernelError::PatchRejected(vec![ + Mismatch::NoCanonicalChange, + ])); + } + Ok(WorldEffect::LensWeightsReplaced { + weights: weights.clone(), + }) + } + } +} + +/// A system capability is admitted for exactly one command body and nothing +/// else. Stated once here, reached by `reduce` and by `apply_effect`. +fn require_system_capability(caller: &CallerId, body: &CommandBody) -> Result<(), KernelError> { + let CallerId::System(capability) = caller else { + return Ok(()); + }; + let admitted = matches!( + (capability, body), + (SystemCapability::Clock, CommandBody::AdvanceTime { .. }) + | (SystemCapability::Play, CommandBody::AdvanceTime { .. }) + | ( + SystemCapability::Elaborator { .. } + | SystemCapability::Consumer { .. } + | SystemCapability::Play, + CommandBody::AdmitPatch { .. } + ) + ); + if admitted { + Ok(()) + } else { + Err(KernelError::Unauthorized) + } +} + +/// The owner may tick from an interface; the tick task may tick with no +/// session. Nothing +/// else may tick. +fn require_clock_caller(state: &WorldState, caller: &CallerId) -> Result<(), KernelError> { + if matches!( + caller, + CallerId::System(SystemCapability::Clock) | CallerId::System(SystemCapability::Play) + ) { + Ok(()) + } else { + require_owner(state, caller) + } +} + +/// Answering is what lets an Active patch declare. Draft answers nothing: +/// `SeedRequest` — the ontology's draft-phase answer — is not inhabited, so +/// genesis and draft elaboration answer nothing. In Active, a patch that only +/// changes components of existing structure is the operator's hand and answers +/// nothing; a patch that declares or admits evidence is elaboration, and +/// elaboration answers a boundary the kernel currently derives or a +/// jurisdiction whose deficit is nonzero. +fn require_answer( + state: &WorldState, + caller: &CallerId, + answers: Option<&PatchAnswer>, + declares: bool, +) -> Result<(), KernelError> { + if caller == &CallerId::System(SystemCapability::Play) && state.phase == WorldPhase::Draft { + return Err(KernelError::WrongPhase { + expected: WorldPhase::Active, + actual: state.phase, + }); + } + match (state.phase, answers) { + (WorldPhase::Draft, None) => Ok(()), + (WorldPhase::Draft, Some(_)) => Err(KernelError::AnswerNotDerived), + (WorldPhase::Active, None) if declares => { + if caller == &CallerId::System(SystemCapability::Play) { + Ok(()) + } else { + Err(KernelError::AnswerRequired) + } + } + (WorldPhase::Active, None) => Ok(()), + (WorldPhase::Active, Some(PatchAnswer::Boundary(claimed))) => { + exact_boundary(state, claimed).map(|_| ()) + } + (WorldPhase::Active, Some(PatchAnswer::Deficit(jurisdiction))) => { + if jurisdiction_deficit(state, *jurisdiction)? > 0 { + Ok(()) + } else { + Err(KernelError::AnswerNotDerived) + } + } + } +} + +/// The total deficit of one jurisdiction, which is what an answer must strictly +/// reduce. +fn jurisdiction_deficit( + state: &WorldState, + jurisdiction: JurisdictionKey, +) -> Result { + Ok(derive_scale_deficit(state)? + .into_iter() + .filter(|row| row.jurisdiction == jurisdiction) + .map(|row| u64::from(row.deficit)) + .sum()) +} + +/// A human principal joins `required_approvers`, so only the lane that builds +/// revision 0 from nothing may bind one. The predicate reads state, never the +/// caller. It takes the two fields it inspects rather than a whole +/// `WorldState` so the genesis lane, which resolves declarations before any +/// `WorldState` exists, can call the same owner instead of hand-copying the +/// literal it would otherwise always evaluate to. +fn admits_human(revision: u64, subjects: &BTreeMap) -> bool { + revision == 0 && subjects.is_empty() +} + +impl WorldState { + /// The world before any structure. Genesis resolves its own patch against + /// this value, so the genesis lane and `AdmitPatch` share one resolver + /// signature instead of hand-passing empty partitions. + fn empty( + world_id: WorldId, + owner: PrincipalId, + title: String, + grammar: Option, + ) -> Self { + Self { + schema: STATE_SCHEMA.into(), + world_id, + revision: 0, + phase: WorldPhase::Draft, + owner, + title, + brief: String::new(), + grammar, + draft_approvals: BTreeSet::new(), + subjects: BTreeMap::new(), + entities: BTreeMap::new(), + edges: BTreeMap::new(), + positions: BTreeMap::new(), + holdings: BTreeMap::new(), + dependencies: BTreeMap::new(), + facts: BTreeMap::new(), + channels: BTreeMap::new(), + knowledge: BTreeMap::new(), + authority: BTreeMap::new(), + selection: BTreeMap::new(), + redress: BTreeMap::new(), + commitments: BTreeMap::new(), + persona_material: BTreeMap::new(), + pressures: BTreeMap::new(), + last_opportunity_at: BTreeMap::new(), + now: FictionalMinutes::default(), + scale_intent: WorldScaleIntent::default(), + // Never persisted: genesis overwrites it, and `verify_state_shape` + // refuses a stored set that never draws. + lens_weights: LensWeights::default(), + controller_assignments: BTreeMap::new(), + affordance_catalog: BTreeMap::new(), + affordance_grants: BTreeMap::new(), + events: Vec::new(), + state_digest: String::new(), + last_commit_digest: None, + } + } + + fn genesis( + world_id: WorldId, + command: &CreateWorld, + effect: &WorldEffect, + ) -> Result { + let WorldEffect::WorldCreated { + owner, + title, + brief, + resolved, + } = effect + else { + return Err(KernelError::Invariant( + "genesis state requires a world-created effect".into(), + )); + }; + validate_principal(&command.owner)?; + let expected_title = normalize_title(&command.title)?; + if owner != &command.owner || title != &expected_title { + return Err(KernelError::Invariant( + "genesis effect does not match the admitted creation command".into(), + )); + } + // The same re-derive-and-compare that `apply_committed_command` runs for + // every other command. Deterministic allocation is what lets one + // equality replace a field-by-field binding zip. + let mut state = Self::empty(world_id, owner.clone(), title.clone(), command.grammar.clone()); + state.brief = brief.clone(); + let expected = patch::resolve_patch( + &state, + command.id, + &command.patch, + Some(&command.scale_intent), + Some(&command.lens_weights), + ) + .map_err(KernelError::PatchRejected)?; + if &expected != resolved { + return Err(KernelError::Invariant( + "genesis effect does not derive from its creation command".into(), + )); + } + require_ruler(&CallerId::Principal(command.owner.clone()), resolved).map_err(|_| { + KernelError::Invariant( + "genesis effect rules or mints without the play authority".into(), + ) + })?; + // Genesis resolves to revision 0 itself: `state.revision` never + // advances past 0 for the creating commit (`resulting_revision: 0`), + // unlike every later commit, which resolves to `state.revision + 1`. + let genesis_revision = state.revision; + admit_resolved(&mut state, resolved, genesis_revision)?; + state.state_digest = state_digest(&state)?; + Ok(state) + } +} + +/// The only writer of every ontology partition. Both admission lanes mutate +/// through it in one fixed order — entities, routes, subjects, operations — so a +/// patch may relocate along a route it declares. It re-derives every structural +/// claim from `state`, so an effect that skipped resolution dies here. +fn admit_resolved( + state: &mut WorldState, + resolved: &ResolvedPatch, + resolves_to: u64, +) -> Result<(), KernelError> { + if resolved.declares_nothing() && resolved.operations.is_empty() { + return Err(KernelError::Invariant( + "admitted patch carries no canonical change".into(), + )); + } + let humans_admitted = admits_human(state.revision, &state.subjects); + for entity in &resolved.entities { + if !patch::is_canonical_text(&entity.entity.label) { + return Err(KernelError::Invariant( + "admitted entity label is not canonical".into(), + )); + } + if let Some(container) = entity.entity.container + && (entity.entity.kind != EntityKind::Place + || state + .entities + .get(&container) + .is_none_or(|record| record.kind != EntityKind::Place)) + { + return Err(KernelError::Invariant( + "admitted container does not name a canonical place".into(), + )); + } + if state + .entities + .insert(entity.entity_id, entity.entity.clone()) + .is_some() + { + return Err(KernelError::Invariant( + "admitted entity ID collision".into(), + )); + } + if !patch::containment_terminates(entity.entity_id, &state.entities) { + return Err(KernelError::Invariant( + "admitted place contains itself".into(), + )); + } + } + for route in &resolved.routes { + let (from, to) = route.edge.endpoints(); + let endpoint_is_place = |entity_id: &EntityId| { + state + .entities + .get(entity_id) + .is_some_and(|record| record.kind == EntityKind::Place) + }; + if !patch::is_canonical_text(route.edge.label()) + || !endpoint_is_place(&from) + || !endpoint_is_place(&to) + || from == to + || !patch::is_valid_cost(route.edge.cost()) + { + return Err(KernelError::Invariant( + "admitted route is noncanonical or does not join two places".into(), + )); + } + if state + .edges + .insert(route.edge_id, route.edge.clone()) + .is_some() + { + return Err(KernelError::Invariant("admitted route ID collision".into())); + } + } + let mut controller_ids: BTreeSet = state + .controller_assignments + .values() + .filter_map(ControllerAssignment::id) + .collect(); + for entry in &resolved.affordances { + // The catalog's only writer holds the same grammar check the resolver + // runs, so an effect resolved elsewhere cannot install an entry the + // bound grammar refuses. + if state.grammar.as_ref().is_some_and(|grammar| { + grammar + .refusal(&entry.affordance.kind, &entry.affordance.roles) + .is_some() + }) { + return Err(KernelError::Invariant( + "admitted affordance is outside the bound grammar".into(), + )); + } + if state + .affordance_catalog + .insert(entry.affordance_id, entry.affordance.clone()) + .is_some() + { + return Err(KernelError::Invariant( + "admitted affordance ID collision".into(), + )); + } + } + // The subjects map's only writer holds the same injectivity the resolver + // checks, decided by the same function. + { + let held = patch::held_import_keys(state.subjects.values()); + let mut declared = BTreeSet::new(); + for subject in &resolved.subjects { + if let Some(key) = &subject.subject.import_key + && patch::import_key_fault(key, &held, &mut declared).is_some() + { + return Err(KernelError::Invariant( + "admitted subject's import key is malformed, held or repeated".into(), + )); + } + } + } + for subject in &resolved.subjects { + let scope = DecisionScope { + subject_id: subject.subject_id, + }; + if !patch::is_canonical_text(&subject.subject.label) { + return Err(KernelError::Invariant( + "admitted subject label is not canonical".into(), + )); + } + validate_assignment(&subject.controller)?; + if matches!(subject.controller, ControllerAssignment::Human { .. }) && !humans_admitted { + return Err(KernelError::Invariant( + "only world genesis may bind a human controller".into(), + )); + } + // Controller-shaped, both ways: a mirror receives no affordance, and + // every other controller must receive one. That is what makes the + // mirror's exclusion from opportunity derivation consistent rather than + // merely enforced. + if matches!( + subject.controller, + ControllerAssignment::ExternallyControlled { .. } + ) != subject.affordances.is_empty() + { + return Err(KernelError::Invariant( + "admitted subject's controller and affordance grant do not pair".into(), + )); + } + if let Some(position) = subject.position + && state + .entities + .get(&position.place) + .is_none_or(|entity| entity.kind != EntityKind::Place) + { + return Err(KernelError::Invariant( + "admitted position does not name a canonical place".into(), + )); + } + if let Some(controller_id) = subject.controller.id() + && !controller_ids.insert(controller_id) + { + return Err(KernelError::Invariant( + "admitted controller ID collision".into(), + )); + } + if state + .subjects + .insert(subject.subject_id, subject.subject.clone()) + .is_some() + || state + .controller_assignments + .insert(scope, subject.controller.clone()) + .is_some() + { + return Err(KernelError::Invariant( + "admitted subject or scope ID collision".into(), + )); + } + if let Some(position) = subject.position + && state + .positions + .insert(subject.subject_id, position) + .is_some() + { + return Err(KernelError::Invariant( + "admitted position collides with an existing one".into(), + )); + } + for affordance_id in &subject.affordances { + if !state.affordance_catalog.contains_key(affordance_id) { + return Err(KernelError::Invariant( + "admitted grant names no catalog entry".into(), + )); + } + state + .affordance_grants + .entry(scope) + .or_default() + .insert(*affordance_id); + } + } + // Facts and channels: one `entities` row and one payload row per + // declaration, written together so the bijection has one writer. + for declared in &resolved.facts { + let claimed_by_a_stranger = match &declared.fact.standing { + FactStanding::Canonical { evidence } => { + !(patch::is_canonical_text(evidence.text()) && resolved.evidence.contains(evidence)) + } + FactStanding::Claimed { by } => !state.subjects.contains_key(by), + FactStanding::Ruled => false, + }; + if !patch::is_canonical_text(&declared.entity.label) + || !patch::is_canonical_text(declared.fact.statement.as_str()) + || declared.entity.kind != EntityKind::Fact + || claimed_by_a_stranger + { + return Err(KernelError::Invariant( + "admitted fact is noncanonical, unevidenced, or asserted by no live subject".into(), + )); + } + if state + .entities + .insert(declared.entity_id, declared.entity.clone()) + .is_some() + || state + .facts + .insert(declared.entity_id, declared.fact.clone()) + .is_some() + { + return Err(KernelError::Invariant("admitted fact ID collision".into())); + } + } + for declared in &resolved.channels { + if !patch::is_canonical_text(&declared.entity.label) + || declared.entity.kind != EntityKind::Channel + || !channel_referents_exist(state, &declared.channel) + { + return Err(KernelError::Invariant( + "admitted channel is noncanonical or names no live reach".into(), + )); + } + if state + .entities + .insert(declared.entity_id, declared.entity.clone()) + .is_some() + || state + .channels + .insert(declared.entity_id, declared.channel.clone()) + .is_some() + { + return Err(KernelError::Invariant( + "admitted channel ID collision".into(), + )); + } + } + if let Some(intent) = &resolved.scale_intent { + state.scale_intent = intent.clone(); + } + if let Some(weights) = &resolved.lens_weights { + state.lens_weights = weights.clone(); + } + apply_operations(state, &resolved.operations, &resolved.evidence, resolves_to) +} + +/// The component writer for every lane: snapshot the before-totals for every +/// resource the operations name, apply each operation, accumulate the ledger +/// deltas, and prove conservation once. Declaration admission calls it after its +/// declaration loops; an exercised affordance's lowered effects call it +/// directly. One writer, one conservation statement. +/// +/// A forged effect reaches this function without ever passing the resolver, so +/// conservation is re-derived over the committed partitions, against the same +/// equation, with `before` read from state rather than from anything the effect +/// asserts. +fn apply_operations( + state: &mut WorldState, + operations: &[ResolvedOp], + evidence: &[EvidenceRef], + resolves_to: u64, +) -> Result<(), KernelError> { + let mut deltas: BTreeMap = BTreeMap::new(); + for operation in operations { + for resource in operation_resources(operation) { + deltas.entry(resource).or_default().before = resource_total(state, resource); + } + } + for operation in operations { + apply_operation(state, operation, evidence, resolves_to)?; + match operation { + ResolvedOp::Transform { + from_resource, + into_resource, + qty, + .. + } => { + deltas.entry(*from_resource).or_default().spent += u128::from(qty.0); + deltas.entry(*into_resource).or_default().gained += u128::from(qty.0); + } + ResolvedOp::Consume { resource, qty, .. } => { + deltas.entry(*resource).or_default().consumed += u128::from(qty.0); + } + ResolvedOp::Admit { resource, qty, .. } => { + deltas.entry(*resource).or_default().admitted += u128::from(qty.0); + } + ResolvedOp::Mint { resource, qty, .. } => { + deltas.entry(*resource).or_default().admitted += u128::from(qty.0); + } + _ => {} + } + } + for (resource, delta) in &mut deltas { + delta.after = resource_total(state, *resource); + } + if patch::check_ledger(&deltas).is_some() { + return Err(KernelError::Invariant("custody does not conserve".into())); + } + // Disjointness, re-derived over the committed partitions for the same + // reason conservation is: a forged effect reaches this function without + // passing the resolver. + if operations.iter().any(|operation| { + matches!( + operation, + ResolvedOp::GrantAuthority { .. } + | ResolvedOp::OpenOffice { .. } + | ResolvedOp::InstallIncumbent { .. } + ) + }) && overlapping_holder(state).is_some() + { + return Err(KernelError::Invariant( + "one subject holds two overlapping jurisdictions of one kind".into(), + )); + } + Ok(()) +} + +/// Every resource an operation names, so `admit_resolved` can read its committed +/// total before touching it. +fn operation_resources(operation: &ResolvedOp) -> Vec { + match operation { + ResolvedOp::Transfer { resource, .. } + | ResolvedOp::Consume { resource, .. } + | ResolvedOp::Admit { resource, .. } + | ResolvedOp::Mint { resource, .. } => vec![*resource], + ResolvedOp::Transform { + from_resource, + into_resource, + .. + } => vec![*from_resource, *into_resource], + _ => Vec::new(), + } +} + +fn resource_total(state: &WorldState, resource: EntityId) -> u128 { + state + .holdings + .values() + .filter_map(|held| held.get(&resource)) + .map(|quantity| u128::from(quantity.0)) + .sum() +} + +/// What a holder holds. Absence is zero. +fn held(state: &WorldState, holder: SubjectId, resource: EntityId) -> u64 { + state + .holdings + .get(&holder) + .and_then(|held| held.get(&resource)) + .map_or(0, |quantity| quantity.0) +} + +/// Zero removes the resource key, and an emptied holder removes the holder key, +/// so `holdings` has exactly one representation of nothing. +fn set_held(state: &mut WorldState, holder: SubjectId, resource: EntityId, value: u64) { + if value == 0 { + let empty = if let Some(held) = state.holdings.get_mut(&holder) { + held.remove(&resource); + held.is_empty() + } else { + false + }; + if empty { + state.holdings.remove(&holder); + } + } else { + state + .holdings + .entry(holder) + .or_default() + .insert(resource, Quantity(value)); + } +} + +/// Whether a subject and a resource are both canonical and of the right kind. +fn custody_referents_exist(state: &WorldState, holder: SubjectId, resource: EntityId) -> bool { + state.subjects.contains_key(&holder) + && state + .entities + .get(&resource) + .is_some_and(|record| record.kind == EntityKind::Resource) +} + +fn dependency_target_exists(state: &WorldState, target: DependencyTarget) -> bool { + match target { + DependencyTarget::Resource(entity_id) => state + .entities + .get(&entity_id) + .is_some_and(|record| record.kind == EntityKind::Resource), + DependencyTarget::Route(edge_id) => state.edges.contains_key(&edge_id), + DependencyTarget::Subject(subject_id) => state.subjects.contains_key(&subject_id), + } +} + +/// The component half of admission. Every precondition is re-derived from the +/// partitions, so a forged operation cannot assert a move the topology refuses. +fn apply_operation( + state: &mut WorldState, + operation: &ResolvedOp, + evidence: &[EvidenceRef], + resolves_to: u64, +) -> Result<(), KernelError> { + let insufficient = || KernelError::Invariant("holder does not hold enough".into()); + let overflow = || KernelError::Invariant("holding would overflow".into()); + let unknown = || KernelError::Invariant("custody operation names no canonical referent".into()); + let zero = || KernelError::Invariant("custody operation moves nothing".into()); + match operation { + ResolvedOp::Relocate { + subject_id, + edge_id, + } => { + let route = state + .edges + .get(edge_id) + .ok_or_else(|| KernelError::Invariant("relocation names no route".into()))?; + let (from, to) = route.endpoints(); + let open = route.is_open(); + let access = route.access().clone(); + if !open + || state.positions.get(subject_id) != Some(&Position { place: from }) + || !patch::route_admits(state, &subject_authority(state, *subject_id), &access, to) + { + return Err(KernelError::Invariant( + "relocation does not traverse an open route the subject may take from its place" + .into(), + )); + } + state.positions.insert(*subject_id, Position { place: to }); + } + ResolvedOp::OpenRoute { edge_id } | ResolvedOp::CloseRoute { edge_id } => { + let open = matches!(operation, ResolvedOp::OpenRoute { .. }); + let route = state + .edges + .get_mut(edge_id) + .ok_or_else(|| KernelError::Invariant("route operation names no route".into()))?; + if route.is_open() == open { + return Err(KernelError::Invariant( + "route operation changes nothing".into(), + )); + } + route.set_open(open); + } + ResolvedOp::AlterCost { edge_id, cost } => { + if !patch::is_valid_cost(*cost) { + return Err(KernelError::Invariant( + "admitted cost is out of range".into(), + )); + } + let route = state + .edges + .get_mut(edge_id) + .ok_or_else(|| KernelError::Invariant("route operation names no route".into()))?; + if route.cost() == *cost { + return Err(KernelError::Invariant( + "route operation changes nothing".into(), + )); + } + route.set_cost(*cost); + } + ResolvedOp::Transfer { + from, + to, + resource, + qty, + } => { + if !custody_referents_exist(state, *from, *resource) || !state.subjects.contains_key(to) + { + return Err(unknown()); + } + if qty.0 == 0 || from == to { + return Err(zero()); + } + let remaining = held(state, *from, *resource) + .checked_sub(qty.0) + .ok_or_else(insufficient)?; + let credited = held(state, *to, *resource) + .checked_add(qty.0) + .ok_or_else(overflow)?; + set_held(state, *from, *resource, remaining); + set_held(state, *to, *resource, credited); + } + ResolvedOp::Transform { + holder, + from_resource, + into_resource, + qty, + } => { + if !custody_referents_exist(state, *holder, *from_resource) + || !custody_referents_exist(state, *holder, *into_resource) + { + return Err(unknown()); + } + if qty.0 == 0 || from_resource == into_resource { + return Err(zero()); + } + let remaining = held(state, *holder, *from_resource) + .checked_sub(qty.0) + .ok_or_else(insufficient)?; + let gained = held(state, *holder, *into_resource) + .checked_add(qty.0) + .ok_or_else(overflow)?; + set_held(state, *holder, *from_resource, remaining); + set_held(state, *holder, *into_resource, gained); + } + ResolvedOp::Consume { + holder, + resource, + qty, + } => { + if !custody_referents_exist(state, *holder, *resource) { + return Err(unknown()); + } + if qty.0 == 0 { + return Err(zero()); + } + let remaining = held(state, *holder, *resource) + .checked_sub(qty.0) + .ok_or_else(insufficient)?; + set_held(state, *holder, *resource, remaining); + } + ResolvedOp::Admit { + holder, + resource, + qty, + evidence: cited, + } => { + if !custody_referents_exist(state, *holder, *resource) { + return Err(unknown()); + } + if qty.0 == 0 { + return Err(zero()); + } + if !evidence.contains(cited) { + return Err(KernelError::Invariant( + "admitted quantity cites no evidence in its patch".into(), + )); + } + let admitted = held(state, *holder, *resource) + .checked_add(qty.0) + .ok_or_else(overflow)?; + set_held(state, *holder, *resource, admitted); + } + ResolvedOp::Mint { + holder, + resource, + qty, + } => { + if !custody_referents_exist(state, *holder, *resource) { + return Err(unknown()); + } + if qty.0 == 0 { + return Err(zero()); + } + let minted = held(state, *holder, *resource) + .checked_add(qty.0) + .ok_or_else(overflow)?; + set_held(state, *holder, *resource, minted); + } + ResolvedOp::Bind { subject, target } | ResolvedOp::Release { subject, target } => { + let bind = matches!(operation, ResolvedOp::Bind { .. }); + if !state.subjects.contains_key(subject) || !dependency_target_exists(state, *target) { + return Err(unknown()); + } + if *target == DependencyTarget::Subject(*subject) { + return Err(KernelError::Invariant( + "a subject cannot depend on itself".into(), + )); + } + let bound = state + .dependencies + .get(subject) + .is_some_and(|targets| targets.contains(target)); + if bound == bind { + return Err(KernelError::Invariant( + "dependency operation changes nothing".into(), + )); + } + if bind { + state + .dependencies + .entry(*subject) + .or_default() + .insert(*target); + } else { + let empty = if let Some(targets) = state.dependencies.get_mut(subject) { + targets.remove(target); + targets.is_empty() + } else { + false + }; + if empty { + state.dependencies.remove(subject); + } + } + } + ResolvedOp::GrantAuthority { holder, grant } + | ResolvedOp::RevokeAuthority { holder, grant } => { + let granting = matches!(operation, ResolvedOp::GrantAuthority { .. }); + if !state.subjects.contains_key(holder) + || !authority_referent_exists(state, grant.over) + || !patch::is_civic_name(&grant.kind.0) + { + return Err(unknown()); + } + let held = state + .authority + .get(holder) + .is_some_and(|grants| grants.contains(grant)); + if held == granting { + return Err(KernelError::Invariant( + "authority operation changes nothing".into(), + )); + } + if granting { + state + .authority + .entry(*holder) + .or_default() + .insert(grant.clone()); + } else { + let empty = if let Some(grants) = state.authority.get_mut(holder) { + grants.remove(grant); + grants.is_empty() + } else { + false + }; + if empty { + state.authority.remove(holder); + } + } + } + ResolvedOp::OpenOffice { + institution, + office, + delegated, + } => { + require_institution(state, *institution, office)?; + if delegated.is_empty() || delegated.iter().any(|kind| !patch::is_civic_name(&kind.0)) { + return Err(KernelError::Invariant( + "an office lends no canonical authority kind".into(), + )); + } + let current = state + .selection + .get(institution) + .and_then(|offices| offices.get(office)); + if current.is_some_and(|seat| &seat.delegated == delegated) { + return Err(KernelError::Invariant( + "office operation changes nothing".into(), + )); + } + // A sitting incumbent survives a reconstitution: clipping an + // office's powers under its holder is a political act, not a + // vacancy. + let incumbent = current.and_then(|seat| seat.incumbent); + state.selection.entry(*institution).or_default().insert( + office.clone(), + Office { + incumbent, + delegated: delegated.clone(), + }, + ); + } + ResolvedOp::CloseOffice { + institution, + office, + } + | ResolvedOp::VacateOffice { + institution, + office, + } => { + let closing = matches!(operation, ResolvedOp::CloseOffice { .. }); + require_institution(state, *institution, office)?; + let no_office = || KernelError::Invariant("office operation names no office".into()); + let offices = state.selection.get_mut(institution).ok_or_else(no_office)?; + let occupied = offices + .get(office) + .map(|seat| seat.incumbent.is_some()) + .ok_or_else(no_office)?; + if closing { + offices.remove(office); + let empty = offices.is_empty(); + if empty { + state.selection.remove(institution); + } + } else if !occupied { + return Err(KernelError::Invariant( + "office operation changes nothing".into(), + )); + } else { + offices.get_mut(office).ok_or_else(no_office)?.incumbent = None; + } + } + ResolvedOp::InstallIncumbent { + institution, + office, + incumbent, + } => { + require_institution(state, *institution, office)?; + if state.subjects.get(incumbent).map(|subject| subject.kind) + != Some(SubjectKind::Person) + { + return Err(KernelError::Invariant( + "an office holder is not a person subject".into(), + )); + } + let offices = state + .selection + .get_mut(institution) + .ok_or_else(|| KernelError::Invariant("office operation names no office".into()))?; + if offices + .iter() + .any(|(name, seat)| name != office && seat.incumbent == Some(*incumbent)) + { + return Err(KernelError::Invariant( + "one person holds two offices of one institution".into(), + )); + } + let seat = offices + .get_mut(office) + .ok_or_else(|| KernelError::Invariant("office operation names no office".into()))?; + if seat.incumbent == Some(*incumbent) { + return Err(KernelError::Invariant( + "office operation changes nothing".into(), + )); + } + seat.incumbent = Some(*incumbent); + } + ResolvedOp::OpenForum { + grievance, + forum, + standing, + } => { + if !state.subjects.contains_key(forum) + || !authority_referent_exists(state, *standing) + || !patch::is_civic_name(&grievance.0) + { + return Err(unknown()); + } + let seat = Forum { + forum: *forum, + standing: *standing, + }; + if state.redress.get(grievance) == Some(&seat) { + return Err(KernelError::Invariant( + "forum operation changes nothing".into(), + )); + } + state.redress.insert(grievance.clone(), seat); + } + ResolvedOp::CloseForum { grievance } => { + if state.redress.remove(grievance).is_none() { + return Err(KernelError::Invariant( + "forum operation names no forum".into(), + )); + } + } + ResolvedOp::AssertClaim { + fact, + statement, + by, + } => { + if !state.subjects.contains_key(by) || !patch::is_canonical_text(statement.as_str()) { + return Err(KernelError::Invariant( + "a claim names no live asserter or no canonical statement".into(), + )); + } + if state + .entities + .insert( + *fact, + EntityRecord { + label: CLAIM_LABEL.into(), + kind: EntityKind::Fact, + container: None, + }, + ) + .is_some() + || state + .facts + .insert( + *fact, + FactRecord { + statement: statement.clone(), + standing: FactStanding::Claimed { by: *by }, + }, + ) + .is_some() + { + return Err(KernelError::Invariant("minted claim ID collision".into())); + } + } + ResolvedOp::AcquireKnowledge { + subject, + fact, + source, + confidence, + } => { + let Some(record) = state.facts.get(fact) else { + return Err(KernelError::Invariant( + "knowledge operation names no canonical fact".into(), + )); + }; + if !state.subjects.contains_key(subject) + || (*source == AuthoredSource::Evidenced + && !matches!(record.standing, FactStanding::Canonical { .. })) + { + return Err(KernelError::Invariant( + "knowledge operation names no live subject, or evidences a claim".into(), + )); + } + let source = match source { + AuthoredSource::Witnessed => KnowledgeSource::Witnessed, + AuthoredSource::Evidenced => KnowledgeSource::Evidenced, + }; + // Compared on `confidence` and `source` alone: `acquired_at` is + // this write's own revision, not part of what the author asserts, + // so a re-assertion identical in everything the author controls + // still refuses as a no-op even though it would land a later + // `acquired_at`. + if state + .knowledge + .get(subject) + .and_then(|held| held.get(fact)) + .is_some_and(|held| held.confidence == *confidence && held.source == source) + { + return Err(KernelError::Invariant( + "knowledge operation changes nothing".into(), + )); + } + // Matches `DecisionEvent.revision` and the `minted_at` scan built + // from it (`action::exercise`, `snapshot`): both name the revision + // this commit resolves to. `resolves_to` is `state.revision` itself + // at genesis, which never advances past 0, and `state.revision + 1` + // everywhere else, since `state` still holds the *previous* + // revision until `submit` bumps it. One value, one caller-computed + // source, so a genesis-seeded row cannot land one revision ahead of + // the state it was written into. + let acquired_at = resolves_to; + let entry = Knowledge { + confidence: *confidence, + source, + acquired_at, + }; + state + .knowledge + .entry(*subject) + .or_default() + .insert(*fact, entry); + } + ResolvedOp::Forget { subject, fact } => { + let (removed, emptied) = state + .knowledge + .get_mut(subject) + .map(|held| { + let removed = held.remove(fact).is_some(); + (removed, held.is_empty()) + }) + .unwrap_or((false, false)); + if !removed { + return Err(KernelError::Invariant( + "knowledge operation changes nothing".into(), + )); + } + if emptied { + state.knowledge.remove(subject); + } + } + ResolvedOp::Communicate { speaker, fact, to } => { + if !state.subjects.contains_key(speaker) || !state.facts.contains_key(fact) { + return Err(KernelError::Invariant( + "a telling names no live speaker or fact".into(), + )); + } + if !can_broadcast(state, *speaker, to) { + return Err(KernelError::Invariant( + "a speaker is outside its own audience".into(), + )); + } + // An empty fan-out is legal: the delta of a telling is a property of + // the world — an empty room, a silenced channel — not a defect in + // the proposal. Speaking alone commits the claim and lands nothing. + // `acquired_at` matches `minted_at` (PA.f44): both name the + // revision this commit resolves to, `resolves_to` (PA.f49) — + // `state.revision` itself at genesis, `state.revision + 1` + // otherwise. + let acquired_at = resolves_to; + for listener in fan_out(state, *speaker, *fact, to) { + state.knowledge.entry(listener).or_default().insert( + *fact, + Knowledge { + confidence: Confidence::Believed, + source: KnowledgeSource::Told { + by: *speaker, + via: to.channel(), + }, + acquired_at, + }, + ); + } + } + ResolvedOp::Display { actor, fact } => { + if !state.subjects.contains_key(actor) || !state.facts.contains_key(fact) { + return Err(KernelError::Invariant( + "a display names no live actor or fact".into(), + )); + } + // The room is the audience, re-derived here: the same derivation + // co-located speech uses, so a body and a voice cannot disagree + // about who is in the room. A placeless actor is refused as a + // placeless speaker is; an empty room is a legal no-op, as + // speaking alone is. `Believed` is fixed by the kernel: a + // displayer cannot choose how much a viewer believes its body. + let room = Audience::Colocated; + if !can_broadcast(state, *actor, &room) { + return Err(KernelError::Invariant( + "an actor displays from no place".into(), + )); + } + // The revision the caller's own commit resolves to: `state.revision` + // itself at genesis, which never advances past 0, and + // `state.revision + 1` everywhere else, since `state` still holds + // the *previous* revision until `submit` bumps it. One value, one + // caller-computed source, so a genesis-seeded row cannot land one + // revision ahead of the state it was written into. + let acquired_at = resolves_to; + for viewer in fan_out(state, *actor, *fact, &room) { + state.knowledge.entry(viewer).or_default().insert( + *fact, + Knowledge { + confidence: Confidence::Believed, + source: KnowledgeSource::Seen { by: *actor }, + acquired_at, + }, + ); + } + } + ResolvedOp::Witness { + fact, + place, + confidence, + } => { + if !state.facts.contains_key(fact) + || !state + .entities + .get(place) + .is_some_and(|record| record.kind == EntityKind::Place) + { + return Err(KernelError::Invariant( + "a witness names no live fact or place".into(), + )); + } + // Recipients are derived here and never stored: everyone standing + // under the place, less everyone who already holds the fact. A + // witness that reaches nobody is refused, because a witnessed event + // is only its reception — `resolve_patch` refuses the same case over + // the candidate graph, so the two layers cannot disagree. + let recipients = unheld(state, *fact, under_place(state, *place)); + if recipients.is_empty() { + return Err(KernelError::Invariant( + "a witness reaches nobody who does not already hold the fact".into(), + )); + } + // The revision the caller's own commit resolves to: `state.revision` + // itself at genesis, which never advances past 0, and + // `state.revision + 1` everywhere else, since `state` still holds + // the *previous* revision until `submit` bumps it. One value, one + // caller-computed source, so a genesis-seeded row cannot land one + // revision ahead of the state it was written into. + let acquired_at = resolves_to; + for witness in recipients { + state.knowledge.entry(witness).or_default().insert( + *fact, + Knowledge { + confidence: *confidence, + source: KnowledgeSource::Witnessed, + acquired_at, + }, + ); + } + } + ResolvedOp::SetPersonaMaterial { subject, material } => { + if !state.subjects.contains_key(subject) + || material + .reads + .keys() + .any(|other| !state.subjects.contains_key(other)) + { + return Err(unknown()); + } + if state.persona_material.get(subject) == Some(material) { + return Err(KernelError::Invariant( + "persona material changes nothing".into(), + )); + } + state.persona_material.insert(*subject, material.clone()); + } + ResolvedOp::SetReach { channel, reach } => { + let current = state + .channels + .get(channel) + .ok_or_else(|| KernelError::Invariant("channel operation names no channel".into()))? + .clone(); + let record = ChannelRecord { + reach: reach.clone(), + controller: current.controller, + }; + if !channel_referents_exist(state, &record) { + return Err(KernelError::Invariant( + "a reach names no live subject or place".into(), + )); + } + if current.reach == *reach { + return Err(KernelError::Invariant( + "channel operation changes nothing".into(), + )); + } + state.channels.insert(*channel, record); + } + ResolvedOp::SetController { + channel, + controller, + } => { + if controller.is_some_and(|subject_id| !state.subjects.contains_key(&subject_id)) { + return Err(unknown()); + } + let seat = state.channels.get_mut(channel).ok_or_else(|| { + KernelError::Invariant("channel operation names no channel".into()) + })?; + if seat.controller == *controller { + return Err(KernelError::Invariant( + "channel operation changes nothing".into(), + )); + } + seat.controller = *controller; + } + ResolvedOp::CreateCommitment { + subject, + key, + commitment, + } => { + if !state.subjects.contains_key(subject) + || !commitment_is_live(state, *subject, commitment) + { + return Err(KernelError::Invariant( + "a commitment names no live promisor, counterparty, or check".into(), + )); + } + if state + .commitments + .entry(*subject) + .or_default() + .insert(*key, commitment.clone()) + .is_some() + { + return Err(KernelError::Invariant("commitment key collision".into())); + } + } + ResolvedOp::DischargeCommitment { subject, key } => { + // One removal, two writes, one owner: the commitment and every + // pressure row it sourced. + let discharged = || KernelError::Invariant("discharge names no live commitment".into()); + let held = state.commitments.get_mut(subject).ok_or_else(discharged)?; + held.remove(key).ok_or_else(discharged)?; + let empty = held.is_empty(); + if empty { + state.commitments.remove(subject); + } + let sourced = PressureSource::Commitment { + subject: *subject, + key: *key, + }; + state.pressures.retain(|_, held| { + held.remove(&sourced); + !held.is_empty() + }); + } + ResolvedOp::AdvancePressure { source, target, by } + | ResolvedOp::ReducePressure { source, target, by } => { + let advancing = matches!(operation, ResolvedOp::AdvancePressure { .. }); + if !state.subjects.contains_key(target) || !pressure_source_is_live(state, source) { + return Err(unknown()); + } + let current = state + .pressures + .get(target) + .and_then(|held| held.get(source)) + .map_or(0, |magnitude| magnitude.0); + let next = if advancing { + current.saturating_add(by.0) + } else { + current.saturating_sub(by.0) + }; + if next == current { + return Err(KernelError::Invariant( + "pressure operation changes nothing".into(), + )); + } + set_pressure(state, *target, *source, next); + } + ResolvedOp::ResolvePressure { source, target } => { + if state + .pressures + .get(target) + .is_none_or(|held| !held.contains_key(source)) + { + return Err(KernelError::Invariant( + "pressure operation changes nothing".into(), + )); + } + set_pressure(state, *target, *source, 0); + } + ResolvedOp::Retire { subject } => { + let scope = DecisionScope { + subject_id: *subject, + }; + let assignment = state.controller_assignments.get(&scope).ok_or_else(unknown)?; + match assignment { + ControllerAssignment::Retired => { + return Err(KernelError::Invariant( + "retire operation names an already retired subject".into(), + )); + } + ControllerAssignment::ExternallyControlled { .. } => { + return Err(KernelError::Invariant( + "retire operation names a mirror this world does not own".into(), + )); + } + // A human's Draft approval cannot be removed by removing the + // human: re-decided here beside the resolver's + // `RetiresAnApprover`, since resolution is speculative and + // this is the actual commit. Active retires the human freely; + // its approval is frozen history by then, judged by replay. + ControllerAssignment::Human { .. } if state.phase == WorldPhase::Draft => { + return Err(KernelError::Invariant( + "retire operation would remove a Draft approver".into(), + )); + } + ControllerAssignment::Human { .. } + | ControllerAssignment::NarrativePersona { .. } + | ControllerAssignment::OperationalAgent { .. } => {} + } + state + .controller_assignments + .insert(scope, ControllerAssignment::Retired); + state.positions.remove(subject); + state.affordance_grants.remove(&scope); + } + ResolvedOp::GrantAffordance { subject, affordance } + | ResolvedOp::RevokeAffordance { subject, affordance } => { + let granting = matches!(operation, ResolvedOp::GrantAffordance { .. }); + let scope = DecisionScope { + subject_id: *subject, + }; + let assignment = state.controller_assignments.get(&scope).ok_or_else(unknown)?; + if assignment.mode().is_none() || !state.affordance_catalog.contains_key(affordance) { + return Err(unknown()); + } + let granted = state + .affordance_grants + .get_mut(&scope) + .ok_or_else(unknown)?; + let held = granted.contains(affordance); + if held == granting { + return Err(KernelError::Invariant( + "affordance grant operation changes nothing".into(), + )); + } + if granting { + granted.insert(*affordance); + } else { + if granted.len() == 1 { + return Err(KernelError::Invariant( + "revoke would leave a controlled subject with no affordance".into(), + )); + } + granted.remove(affordance); + } + } + } + Ok(()) +} + +/// Zero removes the source key, and an emptied target removes the target key, +/// so `pressures` has exactly one representation of nothing. +fn set_pressure(state: &mut WorldState, target: SubjectId, source: PressureSource, value: u32) { + if value == 0 { + let empty = if let Some(held) = state.pressures.get_mut(&target) { + held.remove(&source); + held.is_empty() + } else { + false + }; + if empty { + state.pressures.remove(&target); + } + } else { + state + .pressures + .entry(target) + .or_default() + .insert(source, PressureMagnitude(value)); + } +} + +/// Whether every referent a commitment names is live and its shape holds. +/// Re-derived over the committed partitions, because a forged effect reaches +/// `apply_operation` without ever passing the resolver. +fn commitment_is_live(state: &WorldState, subject: SubjectId, commitment: &Commitment) -> bool { + let counterparty_is_live = match commitment.counterparty { + Some(counterparty) => { + counterparty != subject + && state.subjects.contains_key(&counterparty) + && commitment.kind != CommitmentKind::Goal + } + None => true, + }; + counterparty_is_live + && (commitment.kind == CommitmentKind::Routine) == commitment.period.is_some() + && (commitment.kind == CommitmentKind::Routine || commitment.checks.is_empty()) + && commitment.due > state.now + && commitment + .checks + .iter() + .all(|check| bound_precondition_is_live(state, check)) +} + +fn bound_precondition_is_live(state: &WorldState, check: &BoundPrecondition) -> bool { + let is_kind = |entity_id: &EntityId, kind: EntityKind| { + state + .entities + .get(entity_id) + .is_some_and(|record| record.kind == kind) + }; + let audience_is_live = |via: &Audience| match via { + Audience::Colocated => true, + Audience::Channel(entity_id) => state.channels.contains_key(entity_id), + }; + match check { + BoundPrecondition::Present { at } => is_kind(at, EntityKind::Place), + BoundPrecondition::Reachable { to, within } => { + is_kind(to, EntityKind::Place) && patch::is_valid_cost(*within) + } + BoundPrecondition::Holds { resource, .. } => is_kind(resource, EntityKind::Resource), + BoundPrecondition::Authorized { over, kind } => { + patch::is_civic_name(&kind.0) + && match over { + Target::Subject(subject_id) => state.subjects.contains_key(subject_id), + Target::Entity(entity_id) => is_kind(entity_id, EntityKind::Place), + Target::Edge(edge_id) => state.edges.contains_key(edge_id), + } + } + BoundPrecondition::HasStanding { grievance } => patch::is_civic_name(&grievance.0), + BoundPrecondition::Knows { fact, .. } => is_kind(fact, EntityKind::Fact), + BoundPrecondition::CanBroadcast { via } => audience_is_live(via), + BoundPrecondition::CanReach { subject, via } => { + state.subjects.contains_key(subject) && audience_is_live(via) + } + BoundPrecondition::Committed { to, .. } => state.subjects.contains_key(to), + } +} + +fn pressure_source_is_live(state: &WorldState, source: &PressureSource) -> bool { + match source { + PressureSource::Commitment { subject, key } => state + .commitments + .get(subject) + .is_some_and(|held| held.contains_key(key)), + PressureSource::Dependency(target) => dependency_target_exists(state, *target), + PressureSource::Subject(subject_id) => state.subjects.contains_key(subject_id), + } +} + +/// The label every minted claim carries. A label is a name, not a transcript: +/// the statement is never copied into it and the label is never derived from +/// it. Labels resolve no references, so identical labels across every claim +/// are unremarkable. The statement itself lives in `facts[fact].statement` +/// and is also carried inside the committed `AssertClaim` effect on the +/// event that minted it; `facts` is the one readable home a projection may +/// consult, and the event copy is the replay witness, never a second read +/// surface. +const CLAIM_LABEL: &str = "claim"; + +/// Whether a channel's reach and controller name live structure. +fn channel_referents_exist(state: &WorldState, record: &ChannelRecord) -> bool { + let reach = match &record.reach { + Reach::Subjects(members) => members + .iter() + .all(|subject_id| state.subjects.contains_key(subject_id)), + Reach::Place(place) => state + .entities + .get(place) + .is_some_and(|entity| entity.kind == EntityKind::Place), + }; + reach + && record + .controller + .is_none_or(|subject_id| state.subjects.contains_key(&subject_id)) +} + +/// Whether a subject's controller assignment is `Retired`. The one statement +/// of retirement read by anything downstream of it (audience derivation, +/// preconditions, resolvers): a mirror's assignment is `ExternallyControlled` +/// and is never retired by this check, only an actual `Retire` sets it. +pub(crate) fn is_retired(state: &WorldState, subject_id: SubjectId) -> bool { + matches!( + state.controller_assignments.get(&DecisionScope { subject_id }), + Some(ControllerAssignment::Retired) + ) +} + +/// Everyone standing anywhere under one place. The one downward-facing read of +/// `positions`: `audience`'s `Reach::Place` arm and `ResolvedOp::Witness` are +/// its two callers, so what "under a place" means cannot drift between a +/// declared broadcast area and a witnessed event. A subject with no position is +/// under nothing. +fn under_place(state: &WorldState, root: EntityId) -> BTreeSet { + state + .positions + .iter() + .filter(|(_, position)| patch::covers_place(&state.entities, root, position.place)) + .map(|(subject_id, _)| *subject_id) + .collect() +} + +/// The one statement of reach. Called by both speech preconditions, by a +/// `Communicate`'s admission, and by its apply. Nothing else computes an +/// audience. +/// +/// Co-location is the actor's exact place, not its subtree: a voice fills a +/// room, not the district containing it. A channel's `Reach::Place` is +/// deliberately wider, because a declared broadcast area is a declared choice. +fn audience(state: &WorldState, actor: SubjectId, of: &Audience) -> BTreeSet { + match of { + Audience::Colocated => { + let Some(here) = state.positions.get(&actor).copied() else { + return BTreeSet::new(); + }; + state + .positions + .iter() + .filter(|(_, position)| **position == here) + .map(|(subject_id, _)| *subject_id) + .collect() + } + Audience::Channel(channel) => { + let Some(record) = state.channels.get(channel) else { + return BTreeSet::new(); + }; + match &record.reach { + // Audience derivation is the one owner of who is reachable, so + // a channel may still *declare* a retired member (PA.f33); + // retirement is filtered here, at the single read site, not at + // declaration time. + Reach::Subjects(members) => members + .iter() + .copied() + .filter(|member| !is_retired(state, *member)) + .collect(), + Reach::Place(root) => under_place(state, *root), + } + } + } +} + +/// Whether an actor may broadcast into an audience: either the actor stands +/// inside the declared reach, or — for a channel — the actor is that +/// channel's controller. The controller's privilege is narrow: it lets the +/// horn sound from outside the room, but it does not admit the controller to +/// the audience itself. A controller outside its channel's reach gains no +/// knowledge from its own telling and is not a target another actor can +/// reach through that channel; `audience()` stays the one statement of who is +/// inside, and this is the one statement of who may speak. +fn can_broadcast(state: &WorldState, actor: SubjectId, of: &Audience) -> bool { + if audience(state, actor, of).contains(&actor) { + return true; + } + match of { + Audience::Channel(channel) => state + .channels + .get(channel) + .is_some_and(|record| record.controller == Some(actor)), + Audience::Colocated => false, + } +} + +/// A knowledge landing never overwrites and never downgrades a holder: whoever +/// already holds the fact is dropped, whatever it holds and however it came by +/// it. The knower owns its own credence, and a landing that could reset it by +/// repeating itself would own another subject's mind through an effect nobody +/// checked. `fan_out` and `ResolvedOp::Witness` are the two callers, so a +/// telling and a witnessed event cannot disagree about who is already a knower. +fn unheld( + state: &WorldState, + fact: EntityId, + listeners: BTreeSet, +) -> BTreeSet { + listeners + .into_iter() + .filter(|listener| { + !state + .knowledge + .get(listener) + .is_some_and(|held| held.contains_key(&fact)) + }) + .collect() +} + +/// Who gains knowledge from one telling: the audience, less the speaker, less +/// anyone who already holds the fact. `Believed` is fixed by the kernel and is +/// not a field on the operation, so a speaker cannot choose how much a listener +/// believes it. +fn fan_out( + state: &WorldState, + speaker: SubjectId, + fact: EntityId, + to: &Audience, +) -> BTreeSet { + let mut listeners = audience(state, speaker, to); + listeners.remove(&speaker); + unheld(state, fact, listeners) +} + +/// Whether an authority target names a live subject or a live place. +fn authority_referent_exists(state: &WorldState, target: AuthorityTarget) -> bool { + match target { + AuthorityTarget::Subject(subject_id) => state.subjects.contains_key(&subject_id), + AuthorityTarget::PlaceSubtree(entity_id) => state + .entities + .get(&entity_id) + .is_some_and(|record| record.kind == EntityKind::Place), + } +} + +/// The shared half of every office operation: a canonical office name on a live +/// institution subject. +fn require_institution( + state: &WorldState, + institution: SubjectId, + office: &OfficeName, +) -> Result<(), KernelError> { + if !patch::is_civic_name(&office.0) { + return Err(KernelError::Invariant( + "office name is not canonical".into(), + )); + } + if state.subjects.get(&institution).map(|subject| subject.kind) + != Some(SubjectKind::Institution) + { + return Err(KernelError::Invariant( + "an office was opened on a subject that is not an institution".into(), + )); + } + Ok(()) +} + +/// The subject, if any, whose effective authority holds two grants of one kind +/// over overlapping ground. Re-derived over the committed partitions after every +/// batch that could widen a jurisdiction, so a forged effect cannot install the +/// split-brained state the resolver refuses. +fn overlapping_holder(state: &WorldState) -> Option { + let holders: BTreeSet = state + .authority + .keys() + .copied() + .chain( + state + .selection + .values() + .flat_map(|offices| offices.values()) + .filter_map(|office| office.incumbent), + ) + .collect(); + holders.into_iter().find(|holder| { + let effective: Vec = + subject_authority(state, *holder).into_iter().collect(); + effective.iter().enumerate().any(|(index, one)| { + effective[index + 1..].iter().any(|other| { + one.kind == other.kind + && patch::targets_overlap(&state.entities, one.over, other.over) + }) + }) + }) +} + +/// Exactly the components a subject's verification reads. One owner, consumed by +/// the scope digest and by the snapshot, so the two cannot drift. `routes` is +/// every edge whose `from` or `to` is the subject's place: an inbound route +/// decides who can arrive, and reading too little is a correctness hole while +/// reading too much only costs an extra rejection. `holdings` and `dependencies` +/// are the acting subject's own; a counterparty's holdings do not enter, because +/// a transfer changes both subjects' components and so changes both digests. +/// It also holds what the actor *is* authorized over, and nothing about the +/// world the actor reaches: the target's position, the target's container +/// chain, the forum's state, and any subordinate's components stay out. A +/// realm-wide authority whose preimage held its jurisdiction's occupancy would +/// conflict with every commit in the realm, which is whole-world binding +/// restored by the front door. A target that walks out of a jurisdiction +/// mid-flight therefore fails at `Authorized` rather than rebinding, while a +/// revoked grant is a `ScopeChanged`. +/// +/// `Deserialize` is here so the narrative lane can persist a subject's own +/// components as the "before" an interruption is measured against. No field +/// changes with it, so `ScopePreimage`'s serialization — and therefore every +/// scope digest — is byte-identical. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct ScopeComponents { + position: Option, + routes: BTreeMap, + holdings: BTreeMap, + dependencies: BTreeSet, + /// This subject's own grants. + authority: BTreeSet, + /// What each held office lends: for every office whose incumbent is this + /// subject, the institution's live grants whose kind that office delegates. + /// The institution's authority is copied in through the office link, so one + /// scope digest covers the grant, the office, and the institution's + /// jurisdiction, and only delegated kinds enter — an institution's `judge` + /// jurisdiction never churns a `levy`-only incumbent's proposals. + delegated: BTreeMap>>, + /// The keys of this subject's own knowledge. Keys, not payloads: a statement + /// is immutable, so it cannot change without the key changing, and + /// confidence is admission-only — a re-appraisal that lowers a subject's own + /// confidence does not reject its own in-flight proposal, because `Knows` + /// re-checks at commit and fails closed with `FactUnknown`. + knows: BTreeSet, + /// The channels this subject controls, with their records. Membership of a + /// channel it merely hears never enters: a 1,000-member channel would churn + /// a thousand digests per membership change, which is whole-world binding by + /// the front door. + controls: BTreeMap, + /// This subject's own commitments. `Precondition::Committed` reads them, so + /// the digest must bind them. Pressure, the clock, and the attention stamp + /// stay out: no precondition reads any of the three, so a tick that only + /// advances pressure invalidates no in-flight proposal. + commitments: BTreeMap, +} + +/// Whether an authority target covers a referent. The one statement of +/// jurisdictional membership, reached by `Authorized`, `HasStanding`, +/// `route_admits`, the delegation monotonicity rule, and the snapshot's redress +/// projection. +/// +/// A place subtree covers a subject standing anywhere under it, a place under +/// it, and a route with either endpoint under it — a city must be able to close +/// its own gate, and a gate's far end is outside the city by construction. A +/// resource, fact, or channel is covered by nothing; `RoleKindUnfit` refuses an +/// `Authorized` over such a role at declaration. +fn covers(state: &WorldState, target: AuthorityTarget, of: Target) -> bool { + let under = |place: EntityId, root: EntityId| patch::covers_place(&state.entities, root, place); + match (target, of) { + (AuthorityTarget::Subject(holder), Target::Subject(subject_id)) => holder == subject_id, + (AuthorityTarget::Subject(_), _) => false, + (AuthorityTarget::PlaceSubtree(root), Target::Subject(subject_id)) => state + .positions + .get(&subject_id) + .is_some_and(|position| under(position.place, root)), + (AuthorityTarget::PlaceSubtree(root), Target::Entity(entity_id)) => state + .entities + .get(&entity_id) + .is_some_and(|record| record.kind == EntityKind::Place && under(entity_id, root)), + (AuthorityTarget::PlaceSubtree(root), Target::Edge(edge_id)) => { + state.edges.get(&edge_id).is_some_and(|record| { + let (from, to) = record.endpoints(); + under(from, root) || under(to, root) + }) + } + } +} + +/// Own grants plus what every held office lends. The single statement of what a +/// subject may invoke authority over. There is no precedence between a direct +/// grant and a delegated one, because `OverlappingJurisdiction` makes it +/// impossible for both to answer for one kind over overlapping ground. +fn effective_authority( + own: &BTreeSet, + delegated: &BTreeMap>>, +) -> BTreeSet { + let mut effective = own.clone(); + for lent in delegated.values().flat_map(|offices| offices.values()) { + effective.extend(lent.iter().cloned()); + } + effective +} + +/// Every office this subject occupies, keyed by institution, with what each one +/// lends of that institution's live grants. +fn delegated_authority( + state: &WorldState, + subject_id: SubjectId, +) -> BTreeMap>> { + let mut held: BTreeMap>> = + BTreeMap::new(); + for (institution, offices) in &state.selection { + // A retired institution lends nothing: `Retire` does not vacate + // offices, so the incumbency stays on record, but a dissolved + // institution's grants stop reaching its office-holders here, the one + // site that turns an office into effective authority. + if is_retired(state, *institution) { + continue; + } + for (name, office) in offices { + if office.incumbent != Some(subject_id) { + continue; + } + let lent: BTreeSet = state + .authority + .get(institution) + .into_iter() + .flatten() + .filter(|grant| office.delegated.contains(&grant.kind)) + .cloned() + .collect(); + held.entry(*institution) + .or_default() + .insert(name.clone(), lent); + } + } + held +} + +/// The effective authority of one subject read straight from the partitions, +/// for the reducer paths that do not already hold a `ScopeComponents`. +fn subject_authority(state: &WorldState, subject_id: SubjectId) -> BTreeSet { + let empty = BTreeSet::new(); + effective_authority( + state.authority.get(&subject_id).unwrap_or(&empty), + &delegated_authority(state, subject_id), + ) +} + +fn scope_components(state: &WorldState, subject_id: SubjectId) -> ScopeComponents { + let position = state.positions.get(&subject_id).copied(); + let routes = position + .map(|position| { + state + .edges + .iter() + .filter(|(_, record)| { + let (from, to) = record.endpoints(); + from == position.place || to == position.place + }) + .map(|(edge_id, record)| (*edge_id, record.clone())) + .collect() + }) + .unwrap_or_default(); + ScopeComponents { + position, + routes, + holdings: state.holdings.get(&subject_id).cloned().unwrap_or_default(), + dependencies: state + .dependencies + .get(&subject_id) + .cloned() + .unwrap_or_default(), + authority: state + .authority + .get(&subject_id) + .cloned() + .unwrap_or_default(), + delegated: delegated_authority(state, subject_id), + knows: state + .knowledge + .get(&subject_id) + .into_iter() + .flat_map(BTreeMap::keys) + .copied() + .collect(), + controls: state + .channels + .iter() + .filter(|(_, record)| record.controller == Some(subject_id)) + .map(|(entity_id, record)| (*entity_id, record.clone())) + .collect(), + commitments: state + .commitments + .get(&subject_id) + .cloned() + .unwrap_or_default(), + } +} + +/// The human operator's story feed, derived from the causal record. The events +/// log is not a perception surface: `knowledge` is the sole answer to what a +/// subject may act on and what its projection may contain. +fn operator_log( + state: &WorldState, + invocations: &BTreeMap, +) -> Result, KernelError> { + state + .events + .iter() + .map(|event| { + let speaker = state + .subjects + .get(&event.scope.subject_id) + .ok_or_else(|| KernelError::Invariant("event names no live subject".into()))?; + let invocation = invocations.get(&event.id).ok_or_else(|| { + KernelError::Invariant("event has no committed invocation".into()) + })?; + let entry = state + .affordance_catalog + .get(&event.affordance) + .ok_or_else(|| KernelError::Invariant("event names no catalog entry".into()))?; + let roles = invocation + .bindings + .iter() + .map(|binding| { + let label = match binding.target { + Target::Subject(id) => state.subjects.get(&id).map(|s| s.label.clone()), + Target::Entity(id) => state.entities.get(&id).map(|e| e.label.clone()), + Target::Edge(id) => state.edges.contains_key(&id).then(|| "edge".to_owned()), + }; + label + .map(|target| BoundRole { + role: binding.role.0.clone(), + target, + }) + .ok_or_else(|| KernelError::Invariant("event binds no live referent".into())) + }) + .collect::, _>>()?; + Ok(OperatorEvent { + revision: event.revision, + speaker: event.scope.subject_id, + speaker_label: speaker.label.clone(), + speech: event + .speech + .and_then(|fact| state.facts.get(&fact)) + .map(|record| record.statement.clone()), + display: event + .display + .and_then(|fact| state.facts.get(&fact)) + .map(|record| record.statement.clone()), + verb: entry.kind.0.clone(), + render_path: state + .grammar + .as_ref() + .and_then(|grammar| grammar.verb(&entry.kind.0)) + .map(|verb| verb.render_path), + roles, + }) + }) + .collect() +} + +/// The scheduler's adjacency projection. It is deliberately wider than any +/// subject view — channel reach and place containment are in no subject's +/// snapshot at all — which is exactly why it is derived here, beside +/// `operator_log`, and handed to the cover rather than assembled by a +/// controller organ out of the union of what subjects can see. +/// +/// Nothing here is authority. Two subjects are adjacent when a decision by one +/// can plausibly land on the other, and adjacency only decides which prompt +/// they share. +fn agency_graph(state: &WorldState) -> AgencyGraph { + let active: BTreeSet = state + .controller_assignments + .iter() + .filter(|(_, controller)| { + matches!(controller.mode(), Some(mode) if mode != ControllerMode::Human) + }) + .map(|(scope, _)| scope.subject_id) + .collect(); + let mut graph = AgencyGraph { + subjects: active.iter().copied().collect(), + edges: BTreeSet::new(), + }; + if active.len() < 2 { + return graph; + } + let live = |subject: &SubjectId| active.contains(subject); + + // Place containment, which subsumes "standing in the same room": a place + // covers itself, so one closure states both. + let mut in_place: BTreeMap> = BTreeMap::new(); + for (place, record) in &state.entities { + if record.kind != EntityKind::Place { + continue; + } + let occupants: BTreeSet = state + .positions + .iter() + .filter(|(subject, position)| { + live(subject) && patch::covers_place(&state.entities, *place, position.place) + }) + .map(|(subject, _)| *subject) + .collect(); + if occupants.len() >= 2 { + graph.relate(&occupants); + } + if !occupants.is_empty() { + in_place.insert(*place, occupants); + } + } + + // An open route makes two rooms one neighbourhood. One representative per + // side is enough: each side is already related internally. + for edge in state.edges.values() { + let EdgeRecord::Route { from, to, open, .. } = edge; + if !open { + continue; + } + if let (Some(here), Some(there)) = (in_place.get(from), in_place.get(to)) + && let (Some(one), Some(other)) = (here.first(), there.first()) + { + graph.link(*one, *other); + } + } + + // Dependencies: a named subject is a direct edge, a shared resource or + // route is a star over everyone leaning on it. + let mut shared: BTreeMap> = BTreeMap::new(); + for (subject, targets) in &state.dependencies { + if !live(subject) { + continue; + } + for target in targets { + match target { + DependencyTarget::Subject(other) if live(other) => graph.link(*subject, *other), + DependencyTarget::Subject(_) => {} + other => { + shared.entry(*other).or_default().insert(*subject); + } + } + } + } + for group in shared.values() { + graph.relate(group); + } + + // Authority and office: an institution and the people who hold its seats, + // and a jurisdiction that names one subject as its ground. + for (institution, offices) in &state.selection { + let mut seated: BTreeSet = offices + .values() + .filter_map(|office| office.incumbent) + .filter(live) + .collect(); + if live(institution) { + seated.insert(*institution); + } + graph.relate(&seated); + } + for (holder, grants) in &state.authority { + if !live(holder) { + continue; + } + for grant in grants { + if let AuthorityTarget::Subject(over) = grant.over + && live(&over) + { + graph.link(*holder, over); + } + } + } + + // Channel reach. This is the edge no union of subject views could produce: + // a subject sees the channels it controls, never who else is in earshot. + for record in state.channels.values() { + let mut reached: BTreeSet = match &record.reach { + Reach::Subjects(subjects) => subjects.iter().copied().filter(live).collect(), + Reach::Place(place) => in_place.get(place).cloned().unwrap_or_default(), + }; + if let Some(controller) = record.controller.filter(live) { + reached.insert(controller); + } + graph.relate(&reached); + } + + // Pressure, and the promises that raise it. + for (target, sources) in &state.pressures { + if !live(target) { + continue; + } + for source in sources.keys() { + let other = match source { + PressureSource::Commitment { subject, .. } => Some(*subject), + PressureSource::Dependency(DependencyTarget::Subject(subject)) => Some(*subject), + PressureSource::Subject(subject) => Some(*subject), + PressureSource::Dependency(_) => None, + }; + if let Some(other) = other.filter(live) { + graph.link(*target, other); + } + } + } + for (subject, promises) in &state.commitments { + if !live(subject) { + continue; + } + for commitment in promises.values() { + if let Some(counterparty) = commitment.counterparty.filter(live) { + graph.link(*subject, counterparty); + } + } + } + + graph +} + +fn snapshot(state: &WorldState) -> Result { + // One pass over the causal record so each subject's own knowledge map can be + // stamped with the revision that minted each claim it holds. + let minted_at: BTreeMap = state + .events + .iter() + .flat_map(|event| { + event + .speech + .into_iter() + .chain(event.display) + .map(move |fact| (fact, event.revision)) + }) + .collect(); + // One pass over the causal record so each subject can be stamped with the + // revision of its own last exercised decision. `None` for a subject that + // never acted. + let last_acted_at: BTreeMap = + state + .events + .iter() + .fold(BTreeMap::new(), |mut acc, event| { + let entry = acc.entry(event.scope.subject_id).or_insert(event.revision); + if event.revision > *entry { + *entry = event.revision; + } + acc + }); + let subjects = state + .subjects + .iter() + .map(|(subject_id, subject)| { + let scope = DecisionScope { + subject_id: *subject_id, + }; + let controller = state.controller_assignments.get(&scope).ok_or_else(|| { + KernelError::Invariant("subject has no controller assignment".into()) + })?; + let affordances = state + .affordance_grants + .get(&scope) + .cloned() + .unwrap_or_default(); + let components = scope_components(state, *subject_id); + let offices_held = components + .delegated + .iter() + .flat_map(|(institution, offices)| { + offices + .iter() + .map(move |(office, authority)| OfficeSnapshot { + institution: *institution, + office: office.clone(), + incumbent: Some(*subject_id), + authority: authority.clone(), + }) + }) + .collect(); + let offices_granted = state + .selection + .get(subject_id) + .into_iter() + .flatten() + .map(|(office, seat)| OfficeSnapshot { + institution: *subject_id, + office: office.clone(), + incumbent: seat.incumbent, + authority: state + .authority + .get(subject_id) + .into_iter() + .flatten() + .filter(|grant| seat.delegated.contains(&grant.kind)) + .cloned() + .collect(), + }) + .collect(); + let redress = state + .redress + .iter() + .filter(|(_, forum)| covers(state, forum.standing, Target::Subject(*subject_id))) + .map(|(grievance, forum)| ForumSnapshot { + grievance: grievance.clone(), + forum: forum.forum, + }) + .collect(); + // The sole perception surface, derived here rather than in a + // controller: a controller that recomputed perception would be a + // second answer to who heard what. + let mut knowledge: Vec = state + .knowledge + .get(subject_id) + .into_iter() + .flatten() + .map(|(fact, held)| { + let record = state.facts.get(fact).ok_or_else(|| { + KernelError::Invariant("knowledge names no canonical fact".into()) + })?; + Ok(KnowledgeSnapshot { + fact: *fact, + statement: record.statement.clone(), + standing: match &record.standing { + FactStanding::Canonical { .. } => FactStandingView::Canonical, + FactStanding::Claimed { by } => FactStandingView::Claimed { by: *by }, + FactStanding::Ruled => FactStandingView::Canonical, + }, + confidence: held.confidence, + source: held.source, + minted_at: minted_at.get(fact).copied(), + acquired_at: held.acquired_at, + }) + }) + .collect::, KernelError>>()?; + knowledge.sort_by_key(|entry| (entry.minted_at, entry.fact)); + Ok(SubjectSnapshot { + id: *subject_id, + label: subject.label.clone(), + kind: subject.kind, + import_key: subject.import_key.clone(), + controller_id: controller.id(), + controller_mode: controller.mode(), + human_controller: controller.human_principal().cloned(), + affordances, + position: components.position.map(|position| position.place), + retired: matches!(controller, ControllerAssignment::Retired), + offices_held, + offices_granted, + redress, + knowledge, + commitments: components + .commitments + .iter() + .map(|(key, commitment)| CommitmentSnapshot { + key: *key, + kind: commitment.kind, + counterparty: commitment.counterparty, + due: commitment.due, + period: commitment.period, + statement: commitment.statement.clone(), + past_due: commitment.due <= state.now, + }) + .collect(), + dependencies: components.dependencies.iter().copied().collect(), + components, + material: state.persona_material.get(subject_id).cloned(), + pressures: state + .pressures + .get(subject_id) + .into_iter() + .flatten() + .map(|(source, magnitude)| PressureSnapshot { + source: *source, + magnitude: *magnitude, + }) + .collect(), + qualified: qualifies(state, *subject_id), + last_acted_at: last_acted_at.get(subject_id).copied(), + }) + }) + .collect::, KernelError>>()?; + let places = state + .entities + .iter() + .filter(|(_, record)| record.kind == EntityKind::Place) + .map(|(entity_id, record)| PlaceSnapshot { + id: *entity_id, + label: record.label.clone(), + container: record.container, + }) + .collect(); + let resources = state + .entities + .iter() + .filter(|(_, record)| record.kind == EntityKind::Resource) + .map(|(entity_id, record)| ResourceSnapshot { + id: *entity_id, + label: record.label.clone(), + }) + .collect(); + let routes = state + .edges + .iter() + .map(|(edge_id, record)| { + let (from, to) = record.endpoints(); + RouteSnapshot { + id: *edge_id, + label: record.label().to_owned(), + from, + to, + access: record.access().clone(), + cost: record.cost(), + open: record.is_open(), + } + }) + .collect(); + let channels = state + .channels + .iter() + .map(|(entity_id, record)| ChannelSnapshot { + id: *entity_id, + reach: record.reach.clone(), + controller: record.controller, + }) + .collect(); + // Omniscient and independent of any subject's own knowledge projection: + // a fact nobody has been told or shown is still a row here, and a + // `Ruled` fact keeps its real standing rather than the `Canonical` + // collapse every subject-facing knowledge row applies. + let facts = state + .facts + .iter() + .map(|(fact_id, record)| FactSnapshot { + id: *fact_id, + statement: record.statement.clone(), + standing: match &record.standing { + FactStanding::Canonical { .. } => FactStandingView::Canonical, + FactStanding::Claimed { by } => FactStandingView::Claimed { by: *by }, + FactStanding::Ruled => FactStandingView::Ruled, + }, + known_by: state + .knowledge + .iter() + .filter(|(_, held)| held.contains_key(fact_id)) + .map(|(subject_id, _)| *subject_id) + .collect(), + }) + .collect(); + Ok(WorldSnapshot { + world_id: state.world_id, + revision: state.revision, + phase: state.phase, + owner: state.owner.clone(), + title: state.title.clone(), + brief: state.brief.clone(), + grammar: state.grammar.as_ref().map(GrammarBinding::identity), + draft_approvals: state.draft_approvals.clone(), + required_approvers: required_approvers(state), + subjects, + affordances: state + .affordance_catalog + .iter() + .map(|(affordance_id, entry)| AffordanceSnapshot { + id: *affordance_id, + entry: entry.clone(), + render_path: state + .grammar + .as_ref() + .and_then(|grammar| grammar.verb(&entry.kind.0)) + .map(|verb| verb.render_path), + }) + .collect(), + places, + resources, + routes, + channels, + facts, + opportunities: order_opportunities(state, derive_opportunities(state)?), + now: state.now, + boundaries: derive_boundaries(state)?, + scale_deficit: derive_scale_deficit(state)?, + lens_weights: state.lens_weights.clone(), + state_digest: state.state_digest.clone(), + last_commit_digest: state.last_commit_digest.clone(), + }) +} + +/// A place in the world's causal reach that the world has not yet grown into. +/// Derived, never stored, and cleared by no writer: a boundary stops being +/// derived when its predicate stops holding. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "boundary", rename_all = "snake_case")] +pub enum CausalBoundary { + UnelaboratedDestination { + route: EdgeId, + place: EntityId, + scope: BoundaryDigest, + }, + MissingStructure { + subject: SubjectId, + key: CommitmentKey, + scope: BoundaryDigest, + }, + /// Declared, never derived: no relations partition exists. Answering one is + /// `AnswerNotDerived`. + PolityInCausalRange { + subject: SubjectId, + scope: BoundaryDigest, + }, + /// Declared, never derived: no population membership and no slice concept + /// exists. Answering one is `AnswerNotDerived`. + IndividuationRequired { + population: SubjectId, + scope: BoundaryDigest, + }, +} + +/// The digest of exactly the components that derive one boundary, produced by +/// the one `digest()` owner, in the `ScopeDigest` idiom. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub struct BoundaryDigest(String); + +impl BoundaryDigest { + /// The digest text, for the one command-key derivation that hashes it. + pub(crate) fn text(&self) -> &str { + &self.0 + } + + /// The deficit lane's answer has no preimage of its own: its digest is the + /// session's, produced by the same `sha256:` spelling. + pub(crate) fn from_digest(value: String) -> Self { + Self(value) + } +} + +#[derive(Serialize)] +struct UnelaboratedDestinationPreimage<'a> { + world_id: WorldId, + route: &'a EdgeRecord, + place: &'a EntityRecord, + contained: BTreeSet, + occupants: BTreeSet, + incident: BTreeSet, +} + +#[derive(Serialize)] +struct MissingStructurePreimage<'a> { + world_id: WorldId, + subject: SubjectId, + key: CommitmentKey, + commitment: &'a Commitment, + counterparty_authority: BTreeSet, + redress: &'a BTreeMap, +} + +/// Beside `derive_opportunities`, and reached from `snapshot` and from +/// `reduce`'s `AdmitPatch` arm. The same shape as the opportunity derivation, +/// not the same function: the inputs and the consumers differ, and a shared +/// derivation returning a sum type would be a generic helper wearing a name. +fn derive_boundaries(state: &WorldState) -> Result, KernelError> { + let mut boundaries = Vec::new(); + for (edge_id, record) in &state.edges { + let (from, to) = record.endpoints(); + for place in [from, to] { + let contained: BTreeSet = state + .entities + .iter() + .filter(|(_, entity)| entity.container == Some(place)) + .map(|(entity_id, _)| *entity_id) + .collect(); + let occupants: BTreeSet = state + .positions + .iter() + .filter(|(_, position)| position.place == place) + .map(|(subject_id, _)| *subject_id) + .collect(); + let incident: BTreeSet = state + .edges + .iter() + .filter(|(_, candidate)| { + let (candidate_from, candidate_to) = candidate.endpoints(); + candidate_from == place || candidate_to == place + }) + .map(|(candidate_id, _)| *candidate_id) + .collect(); + if !contained.is_empty() + || !occupants.is_empty() + || incident.len() != 1 + || !incident.contains(edge_id) + { + continue; + } + let entity = state + .entities + .get(&place) + .ok_or_else(|| KernelError::Invariant("a route names no canonical place".into()))?; + boundaries.push(CausalBoundary::UnelaboratedDestination { + route: *edge_id, + place, + scope: BoundaryDigest(digest(&UnelaboratedDestinationPreimage { + world_id: state.world_id, + route: record, + place: entity, + contained, + occupants, + incident, + })?), + }); + } + } + // A commitment the counterparty can neither command nor litigate. Both + // clauses read the civic partitions through their own predicates, so + // jurisdiction lent by an office counts and no second covering rule exists. + // A `Goal` derives nothing: a promise to oneself needs no forum. + for (subject, held) in &state.commitments { + for (key, commitment) in held { + let Some(counterparty) = commitment.counterparty else { + continue; + }; + let counterparty_authority = subject_authority(state, counterparty); + let commandable = counterparty_authority + .iter() + .any(|grant| covers(state, grant.over, Target::Subject(*subject))); + let litigable = state + .redress + .values() + .any(|forum| covers(state, forum.standing, Target::Subject(counterparty))); + if commandable || litigable { + continue; + } + boundaries.push(CausalBoundary::MissingStructure { + subject: *subject, + key: *key, + scope: BoundaryDigest(digest(&MissingStructurePreimage { + world_id: state.world_id, + subject: *subject, + key: *key, + commitment, + counterparty_authority, + redress: &state.redress, + })?), + }); + } + } + Ok(boundaries) +} + +/// The sole validator of a claimed boundary, mirroring `exact_opportunity`. +fn exact_boundary( + state: &WorldState, + claimed: &CausalBoundary, +) -> Result { + derive_boundaries(state)? + .into_iter() + .find(|current| current == claimed) + .ok_or(KernelError::AnswerNotDerived) +} + +/// One region's count for one subject kind. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct ScaleDeficitRow { + pub jurisdiction: JurisdictionKey, + pub kind: SubjectKind, + pub target: u32, + pub qualified: u32, + pub deficit: u32, +} + +/// Whether a subject counts toward the world's scale target. Aliveness is +/// structural and phase-free: a controller, a non-empty grant set, and a held +/// `Goal`. A Draft world's deficit is what the seed lane has left to author; an +/// Active world's is what the elaborator has left to answer. +/// +/// There is no phase clause here because `require_answer` already owns the +/// Draft-answer refusal: it refuses every Draft answer outright, so a phase +/// clause in this predicate would protect nothing and would only pin a Draft +/// world's deficit at the authored intent forever, leaving the seed lane no +/// derived termination. +/// +/// The conjunction is written once, because retirement and grant revocation +/// make the first two clauses live later and a scattered count would then be +/// wrong in three places. "Executable" is structural, never "preconditions +/// currently hold": evaluating them per subject per snapshot would make the +/// deficit flicker as routes open and close. +fn qualifies(state: &WorldState, subject_id: SubjectId) -> bool { + let scope = DecisionScope { subject_id }; + state.controller_assignments.contains_key(&scope) + && state + .affordance_grants + .get(&scope) + .is_some_and(|granted| !granted.is_empty()) + && state.commitments.get(&subject_id).is_some_and(|held| { + held.values() + .any(|commitment| commitment.kind == CommitmentKind::Goal) + }) +} + +/// Derived in `snapshot`, never stored. `snapshot` is the recount: it already +/// re-derives everything, and a second after-every-commit step would be a +/// second owner. Only admitted subjects reduce it, so a rejected patch leaves +/// it visible, which is free — a rejection mutates nothing. +fn derive_scale_deficit(state: &WorldState) -> Result, KernelError> { + let mut counted: BTreeMap<(JurisdictionKey, SubjectKind), u32> = BTreeMap::new(); + for (subject_id, subject) in &state.subjects { + if !qualifies(state, *subject_id) { + continue; + } + match state.positions.get(subject_id) { + // A subject under nested roots counts toward both: layered + // jurisdiction applied to counting. A subject standing somewhere + // no declared root covers still counts, in `Uncovered`, so the + // deficit stays total over every qualifying subject. + Some(position) => { + let mut covered = false; + for root in state.scale_intent.jurisdictions.keys() { + if patch::covers_place(&state.entities, *root, position.place) { + covered = true; + *counted + .entry((JurisdictionKey::PlaceSubtree(*root), subject.kind)) + .or_default() += 1; + } + } + if !covered { + *counted + .entry((JurisdictionKey::Uncovered, subject.kind)) + .or_default() += 1; + } + } + // Counted, visible, and reducing no target. + None => { + *counted + .entry((JurisdictionKey::Uncovered, subject.kind)) + .or_default() += 1; + } + } + } + let mut rows: BTreeMap<(JurisdictionKey, SubjectKind), ScaleDeficitRow> = BTreeMap::new(); + for (kind, world_target) in &state.scale_intent.targets { + for (root, permille) in &state.scale_intent.jurisdictions { + let jurisdiction = JurisdictionKey::PlaceSubtree(*root); + let target = u32::try_from( + u64::from(*world_target) + .checked_mul(u64::from(*permille)) + .ok_or_else(|| KernelError::Invariant("scale target overflow".into()))? + / 1000, + ) + .map_err(|_| KernelError::Invariant("scale target overflow".into()))?; + let qualified = counted + .get(&(jurisdiction, *kind)) + .copied() + .unwrap_or_default(); + rows.insert( + (jurisdiction, *kind), + ScaleDeficitRow { + jurisdiction, + kind: *kind, + target, + qualified, + deficit: target.saturating_sub(qualified), + }, + ); + } + } + for ((jurisdiction, kind), qualified) in counted { + rows.entry((jurisdiction, kind)) + .or_insert(ScaleDeficitRow { + jurisdiction, + kind, + target: 0, + qualified, + deficit: 0, + }) + .qualified = qualified; + } + Ok(rows + .into_values() + .filter(|row| row.target > 0 || row.qualified > 0) + .collect()) +} + +/// A pure re-ordering of `derive_opportunities`' output: same values, same +/// length, same set. Never a filter — filtering by readiness would drag +/// precondition reads into `ScopePreimage`, and a tick could then withdraw an +/// opportunity a controller is mid-inference on, which `exact_opportunity` +/// would report as `OpportunityMismatch` rather than the honest `ScopeChanged`. +/// +/// A subject never attended sorts ahead of every subject that has, and a +/// subject with no pressure still climbs one tick at a time, so the order +/// starves nobody. `SubjectId` is the final tiebreak, so the order is total and +/// identical on every machine. +fn order_opportunities( + state: &WorldState, + mut opportunities: Vec, +) -> Vec { + opportunities.sort_by_key(|opportunity| { + let subject_id = opportunity.scope.subject_id; + ( + std::cmp::Reverse(pressure_total(state, subject_id)), + std::cmp::Reverse(attention_debt(state, subject_id)), + subject_id, + ) + }); + opportunities +} + +fn pressure_total(state: &WorldState, subject_id: SubjectId) -> u64 { + state + .pressures + .get(&subject_id) + .into_iter() + .flat_map(BTreeMap::values) + .fold(0u64, |total, magnitude| { + total.saturating_add(u64::from(magnitude.0)) + }) +} + +/// Minutes since this subject last consumed an opportunity. Absence is +/// `u64::MAX`: never attended outranks every subject that has. +fn attention_debt(state: &WorldState, subject_id: SubjectId) -> u64 { + state + .last_opportunity_at + .get(&subject_id) + .map_or(u64::MAX, |stamp| state.now.since(*stamp)) +} + +fn derive_opportunities(state: &WorldState) -> Result, KernelError> { + if state.phase != WorldPhase::Active { + return Ok(Vec::new()); + } + state + .controller_assignments + .iter() + // World truth, not a scheduling preference: a mirror has no turn, so it + // never mints an opportunity and never trips the empty-grant invariant. + .filter(|(_, controller)| controller.mode().is_some()) + .map(|(scope, controller)| { + let (Some(controller_id), Some(controller_mode)) = (controller.id(), controller.mode()) + else { + return Err(KernelError::Invariant( + "decision scope has no controller turn".into(), + )); + }; + let affordance_ids: Vec<_> = state + .affordance_grants + .get(scope) + .into_iter() + .flatten() + .copied() + .collect(); + if affordance_ids.is_empty() { + return Err(KernelError::Invariant( + "active decision scope has no affordances".into(), + )); + } + Ok(DecisionOpportunity { + world_id: state.world_id, + revision: state.revision, + scope_digest: scope_digest(state, *scope)?, + scope: *scope, + controller_id, + controller_mode, + affordance_ids, + }) + }) + .collect() +} + +/// The entries one scope is granted, paired with their definitions. A grant +/// naming no catalog entry is a corrupt kernel rather than a rejection: one +/// owner writes both partitions in one commit. +fn granted_entries( + state: &WorldState, + scope: DecisionScope, +) -> Result, KernelError> { + state + .affordance_grants + .get(&scope) + .into_iter() + .flatten() + .map(|affordance_id| { + state + .affordance_catalog + .get(affordance_id) + .map(|entry| (*affordance_id, entry)) + .ok_or_else(|| KernelError::Invariant("granted affordance has no entry".into())) + }) + .collect() +} + +/// One affordance the kernel has already gated: the opportunity offers this +/// entry, the scope holds it, and `entry` is its catalog definition. It is the +/// only way to name an affordance to `action::exercise`, so a caller cannot +/// reach the invocation pipeline without passing the grant check first. +pub(crate) struct GrantedAffordance<'a> { + pub(crate) id: AffordanceId, + pub(crate) entry: &'a Affordance, +} + +/// The membership half of the affordance check, shared by `reduce` and +/// `apply_effect`: the opportunity offers the entry and the scope holds it. It +/// returns the entry rather than a unit, so the gate and the lookup are one act. +fn require_granted<'a>( + state: &'a WorldState, + current: &DecisionOpportunity, + affordance: AffordanceId, +) -> Result, KernelError> { + if current.affordance_ids.contains(&affordance) + && state + .affordance_grants + .get(¤t.scope) + .is_some_and(|granted| granted.contains(&affordance)) + { + let entry = state + .affordance_catalog + .get(&affordance) + .ok_or_else(|| KernelError::Invariant("granted affordance has no entry".into()))?; + Ok(GrantedAffordance { + id: affordance, + entry, + }) + } else { + Err(KernelError::AffordanceDenied) + } +} + +/// The sole producer of a `ScopeDigest`. The components it reads come from +/// `scope_components`, which the snapshot reads too. +fn scope_digest(state: &WorldState, scope: DecisionScope) -> Result { + let controller = state + .controller_assignments + .get(&scope) + .ok_or_else(|| KernelError::Invariant("decision scope has no controller".into()))?; + let affordances = granted_entries(state, scope)?; + let components = scope_components(state, scope.subject_id); + digest(&ScopePreimage { + world_id: state.world_id, + subject_id: scope.subject_id, + controller, + affordances, + components: &components, + }) + .map(ScopeDigest) +} + +/// Binding, which is one of the two checks a committed invocation passes. +/// Binding is scope-digest equality: has what the proposal was made against +/// moved? Admission — preconditions, effect ceilings, and the band draw, all in +/// `action::exercise` — is the other, and it runs at commit against the same +/// revision the digest was verified at. A component that admission reads but +/// binding does not is therefore fail-closed by re-check at commit rather than +/// by rejecting the proposal when it changes. +fn exact_opportunity( + state: &WorldState, + claimed: &DecisionOpportunity, +) -> Result { + if claimed.world_id != state.world_id { + return Err(KernelError::OpportunityMismatch); + } + let current = derive_opportunities(state)? + .into_iter() + .find(|current| current.scope == claimed.scope) + .ok_or(KernelError::OpportunityMismatch)?; + if claimed.revision > state.revision { + return Err(KernelError::OpportunityMismatch); + } + if current.scope_digest != claimed.scope_digest { + return Err(KernelError::ScopeChanged { + scope: claimed.scope, + expected: claimed.scope_digest.clone(), + actual: current.scope_digest, + }); + } + Ok(current) +} + +fn required_approvers(state: &WorldState) -> BTreeSet { + std::iter::once(state.owner.clone()) + .chain( + state + .controller_assignments + .values() + .filter_map(ControllerAssignment::human_principal) + .cloned(), + ) + .collect() +} + +/// Who may admit a patch, and inside what. `None` means unconfined: the owner. +/// Reached from `reduce`'s `AdmitPatch` arm and re-reached from `apply_effect`'s +/// `PatchAdmitted` arm, per the file's idiom that `reduce` decides and +/// `apply_effect` re-decides. +fn require_patch_author( + state: &WorldState, + caller: &CallerId, + answers: Option<&PatchAnswer>, +) -> Result, KernelError> { + match caller { + CallerId::Principal(principal) if principal == &state.owner => Ok(None), + CallerId::System(SystemCapability::Play) => Ok(None), + CallerId::System(SystemCapability::Elaborator { jurisdiction }) => { + let answer = answers.ok_or(KernelError::Unauthorized)?; + let ground = PatchGround::Jurisdiction(*jurisdiction); + if !ground_covers(state, ground, answer) { + return Err(KernelError::Unauthorized); + } + Ok(Some(ground)) + } + CallerId::System(SystemCapability::Consumer { consumer }) => { + // Authority over its own mirrors is not jurisdictional and does not + // depend on an answer. An answer, when present, must name a subject + // this consumer is bound to, so a consumer cannot claim credit for + // structure it is confined out of writing. + let ground = PatchGround::Consumer(*consumer); + if let Some(answer) = answers + && !ground_covers(state, ground, answer) + { + return Err(KernelError::Unauthorized); + } + Ok(Some(ground)) + } + _ => Err(KernelError::Unauthorized), + } +} + +/// Does the caller's jurisdiction cover the thing the answer names? +/// +/// Two coverings, deliberately asymmetric. A boundary is covered +/// **transitively** through `covers_place`, so a parent jurisdiction's +/// elaborator may answer a boundary in a nested child. A deficit is covered by +/// **exact key equality**: a subject under nested roots counts toward both +/// roots' targets, so a parent answering a child's row would reduce two targets +/// with one subject and drain a child's queue while its own row stays red. +/// Boundaries name a thing; deficits name a row. +/// A consumer's arm is narrower on purpose: it may answer only a +/// `MissingStructure` boundary on one of its own mirrors. A deficit is +/// jurisdictional and a consumer holds no jurisdiction; a boundary about a +/// foreign subject is not its business. +fn ground_covers(state: &WorldState, held: PatchGround, answer: &PatchAnswer) -> bool { + let held = match held { + PatchGround::Jurisdiction(jurisdiction) => jurisdiction, + PatchGround::Consumer(consumer) => { + let PatchAnswer::Boundary(CausalBoundary::MissingStructure { subject, .. }) = answer + else { + return false; + }; + return bound_to_consumer(state, *subject, consumer); + } + }; + match answer { + PatchAnswer::Boundary(CausalBoundary::UnelaboratedDestination { place, .. }) => { + place_in(state, held, *place) + } + // The two never-derived variants join this clause only so the match is + // total; `exact_boundary` refuses them before authority is read. + PatchAnswer::Boundary( + CausalBoundary::MissingStructure { subject, .. } + | CausalBoundary::PolityInCausalRange { subject, .. } + | CausalBoundary::IndividuationRequired { + population: subject, + .. + }, + ) => match state.positions.get(subject) { + Some(position) => place_in(state, held, position.place), + None => held == JurisdictionKey::Uncovered, + }, + PatchAnswer::Deficit(key) => *key == held, + } +} + +/// Is this committed subject one of that consumer's mirrors? The consumer's +/// ground is derived here, at decision time, and never carried on the wire: a +/// binding a later commit revoked shrinks the consumer's authority with no +/// ingress change. +fn bound_to_consumer(state: &WorldState, subject: SubjectId, consumer: ConsumerId) -> bool { + state + .controller_assignments + .get(&DecisionScope { + subject_id: subject, + }) + .and_then(ControllerAssignment::consumer) + == Some(consumer) +} + +fn place_in(state: &WorldState, held: JurisdictionKey, place: EntityId) -> bool { + match held { + JurisdictionKey::PlaceSubtree(root) => patch::covers_place(&state.entities, root, place), + JurisdictionKey::Uncovered => false, + } +} + +/// The ground a patch writes on, as one map over `state ∪ patch`, so a place +/// declared and built on in the same patch confines through the chain it +/// declares. +fn candidate_places( + state: &WorldState, + resolved: &ResolvedPatch, +) -> BTreeMap { + let mut entities = state.entities.clone(); + for declared in &resolved.entities { + entities.insert(declared.entity_id, declared.entity.clone()); + } + for declared in &resolved.facts { + entities.insert(declared.entity_id, declared.entity.clone()); + } + for declared in &resolved.channels { + entities.insert(declared.entity_id, declared.entity.clone()); + } + entities +} + +/// Every place-or-subject referent a jurisdictional author writes must sit under +/// its jurisdiction. Returns the complete set, like every other check. +/// +/// Placeless referents — resource kinds, catalog entries, canonical facts — +/// name no ground and are not confined. A place declared with no container is a +/// new jurisdiction root and is the owner's act. There is no relevance test: a +/// patch that satisfies its answer may also declare unrelated structure inside +/// its jurisdiction, because "the minimum the boundary needs" is a semantic +/// verdict the kernel must not hold. +fn confine_to_ground( + state: &WorldState, + resolved: &ResolvedPatch, + held: PatchGround, +) -> Result<(), Vec> { + let entities = candidate_places(state, resolved); + // A consumer names no ground, so every place, every route, and every + // place-shaped reach is refused with no extra rule: relocation, route + // opening and closing, cost changes, and place-subtree grants are + // unrepresentable for it because they carry a place or a route. + let inside = |place: EntityId| match held { + PatchGround::Jurisdiction(JurisdictionKey::PlaceSubtree(root)) => { + patch::covers_place(&entities, root, place) + } + PatchGround::Jurisdiction(JurisdictionKey::Uncovered) | PatchGround::Consumer(_) => false, + }; + // Every subject's consumer binding over `state ∪ patch`, so a consumer's + // first document can declare its own mirror and write it in one patch. + let mut bindings: BTreeMap> = state + .controller_assignments + .iter() + .map(|(scope, assignment)| (scope.subject_id, assignment.consumer())) + .collect(); + for declared in &resolved.subjects { + bindings.insert(declared.subject_id, declared.controller.consumer()); + } + let mut positions: BTreeMap> = state + .positions + .iter() + .map(|(subject, position)| (*subject, Some(position.place))) + .collect(); + for declared in &resolved.subjects { + positions.insert( + declared.subject_id, + declared.position.map(|position| position.place), + ); + } + let mut edges: BTreeMap = state + .edges + .iter() + .map(|(edge_id, record)| (*edge_id, record.endpoints())) + .collect(); + for declared in &resolved.routes { + edges.insert(declared.edge_id, declared.edge.endpoints()); + } + + let mut mismatches = Vec::new(); + let mut confine_subject = |site: &Site, subject: SubjectId, mismatches: &mut Vec| { + let admitted = match held { + PatchGround::Jurisdiction(jurisdiction) => { + match positions.get(&subject).copied().flatten() { + Some(place) => inside(place), + None => jurisdiction == JurisdictionKey::Uncovered, + } + } + // Position is unconfined for a consumer: what binds a mirror is who + // controls it, not where it stands. + PatchGround::Consumer(consumer) => { + bindings.get(&subject).copied().flatten() == Some(consumer) + } + }; + if !admitted { + mismatches.push(Mismatch::OutsideJurisdiction { site: site.clone() }); + } + }; + let mut confine_place = |site: &Site, place: EntityId, mismatches: &mut Vec| { + if !inside(place) { + mismatches.push(Mismatch::OutsideJurisdiction { site: site.clone() }); + } + }; + + for declared in &resolved.subjects { + let site = Site::Declaration(declared.handle.clone()); + confine_subject(&site, declared.subject_id, &mut mismatches); + } + for declared in &resolved.entities { + if declared.entity.kind != EntityKind::Place { + continue; + } + let site = Site::Declaration(declared.handle.clone()); + match declared.entity.container { + Some(container) => confine_place(&site, container, &mut mismatches), + // A root is the owner's act. An elaborator elaborates inside one. + None => mismatches.push(Mismatch::OutsideJurisdiction { site }), + } + } + for declared in &resolved.routes { + let site = Site::Declaration(declared.handle.clone()); + let (from, to) = declared.edge.endpoints(); + confine_place(&site, from, &mut mismatches); + confine_place(&site, to, &mut mismatches); + } + for declared in &resolved.facts { + let site = Site::Declaration(declared.handle.clone()); + match declared.fact.standing { + FactStanding::Claimed { by } => confine_subject(&site, by, &mut mismatches), + // A consumer's citation is its own provenance claim, and that claim + // buys an `Admit` into its own custody and a claimed fact. It + // cannot canonize. + FactStanding::Canonical { .. } => { + if matches!(held, PatchGround::Consumer(_)) { + mismatches.push(Mismatch::OutsideJurisdiction { site }); + } + } + // Redundant with `require_ruler`, which refuses a confined caller's + // `Ruled` fact outright; kept so this match stays total. + FactStanding::Ruled => { + mismatches.push(Mismatch::OutsideJurisdiction { site }); + } + } + } + for declared in &resolved.channels { + let site = Site::Declaration(declared.handle.clone()); + match &declared.channel.reach { + Reach::Place(place) => confine_place(&site, *place, &mut mismatches), + Reach::Subjects(subjects) => { + for subject in subjects { + confine_subject(&site, *subject, &mut mismatches); + } + } + } + if let Some(controller) = declared.channel.controller { + confine_subject(&site, controller, &mut mismatches); + } + } + for (index, operation) in resolved.operations.iter().enumerate() { + let site = Site::Operation(index); + // Retirement and an affordance grant are authority over the subject's + // standing, not structure over ground: a confined author is refused + // whatever place the subject stands under, exactly as `require_ruler` + // refuses a `Ruled` fact or a `Mint` outright. The owner is unconfined + // and never reaches this clause. + if matches!( + operation, + ResolvedOp::Retire { .. } + | ResolvedOp::GrantAffordance { .. } + | ResolvedOp::RevokeAffordance { .. } + ) { + mismatches.push(Mismatch::OutsideJurisdiction { site: site.clone() }); + continue; + } + let (subjects, places, routes) = operation_ground(operation, &entities); + for subject in subjects { + confine_subject(&site, subject, &mut mismatches); + } + for place in places { + confine_place(&site, place, &mut mismatches); + } + for route in routes { + match edges.get(&route) { + Some((from, to)) => { + confine_place(&site, *from, &mut mismatches); + confine_place(&site, *to, &mut mismatches); + } + None => mismatches.push(Mismatch::OutsideJurisdiction { site: site.clone() }), + } + } + } + mismatches.sort(); + mismatches.dedup(); + if mismatches.is_empty() { + Ok(()) + } else { + Err(mismatches) + } +} + +/// The one author of a `Ruled` fact and a `Mint`. `Ok` when the caller is +/// `System(Play)`. Otherwise, one `Mismatch::RuledWithoutAuthority` per +/// `Ruled` fact and per `Mint`, and `Ok` if there are none. Called in +/// `reduce`'s `AdmitPatch` arm right after `resolve_patch` and before +/// confinement, and re-decided in `apply_effect`'s `PatchAdmitted` arm. The +/// resolver stays actor-blind: this runs after resolution, never inside it. +fn require_ruler(caller: &CallerId, resolved: &ResolvedPatch) -> Result<(), Vec> { + if caller == &CallerId::System(SystemCapability::Play) { + return Ok(()); + } + let mut mismatches = Vec::new(); + for declared in &resolved.facts { + if matches!(declared.fact.standing, FactStanding::Ruled) { + mismatches.push(Mismatch::RuledWithoutAuthority { + site: Site::Declaration(declared.handle.clone()), + }); + } + } + for (index, operation) in resolved.operations.iter().enumerate() { + if matches!(operation, ResolvedOp::Mint { .. }) { + mismatches.push(Mismatch::RuledWithoutAuthority { + site: Site::Operation(index), + }); + } + } + if mismatches.is_empty() { + Ok(()) + } else { + Err(mismatches) + } +} + +/// The ground one lowered operation touches: the subjects whose position it +/// must sit under, the places it names directly, and the routes whose endpoints +/// it must sit under. Total over `ResolvedOp`, so a new operation cannot ship +/// without saying where it lands. +fn operation_ground( + operation: &ResolvedOp, + entities: &BTreeMap, +) -> (Vec, Vec, Vec) { + // A resource, a fact, and a channel are placeless referents: they name no + // ground, so only a place among the named entities confines. + let places = |candidates: Vec| { + candidates + .into_iter() + .filter(|entity_id| { + entities + .get(entity_id) + .is_some_and(|record| record.kind == EntityKind::Place) + }) + .collect() + }; + match operation { + ResolvedOp::Relocate { + subject_id, + edge_id, + } => (vec![*subject_id], Vec::new(), vec![*edge_id]), + ResolvedOp::OpenRoute { edge_id } | ResolvedOp::CloseRoute { edge_id } => { + (Vec::new(), Vec::new(), vec![*edge_id]) + } + ResolvedOp::AlterCost { edge_id, .. } => (Vec::new(), Vec::new(), vec![*edge_id]), + ResolvedOp::Transfer { + from, to, resource, .. + } => (vec![*from, *to], places(vec![*resource]), Vec::new()), + ResolvedOp::Transform { + holder, + from_resource, + into_resource, + .. + } => ( + vec![*holder], + places(vec![*from_resource, *into_resource]), + Vec::new(), + ), + ResolvedOp::Consume { + holder, resource, .. + } + | ResolvedOp::Admit { + holder, resource, .. + } + | ResolvedOp::Mint { + holder, resource, .. + } => (vec![*holder], places(vec![*resource]), Vec::new()), + ResolvedOp::Bind { subject, target } | ResolvedOp::Release { subject, target } => { + match target { + DependencyTarget::Subject(other) => { + (vec![*subject, *other], Vec::new(), Vec::new()) + } + DependencyTarget::Route(edge_id) => (vec![*subject], Vec::new(), vec![*edge_id]), + DependencyTarget::Resource(resource) => { + (vec![*subject], places(vec![*resource]), Vec::new()) + } + } + } + ResolvedOp::GrantAuthority { holder, grant } + | ResolvedOp::RevokeAuthority { holder, grant } => match grant.over { + AuthorityTarget::Subject(other) => (vec![*holder, other], Vec::new(), Vec::new()), + AuthorityTarget::PlaceSubtree(root) => (vec![*holder], vec![root], Vec::new()), + }, + ResolvedOp::OpenOffice { institution, .. } + | ResolvedOp::CloseOffice { institution, .. } + | ResolvedOp::VacateOffice { institution, .. } => { + (vec![*institution], Vec::new(), Vec::new()) + } + ResolvedOp::InstallIncumbent { + institution, + incumbent, + .. + } => (vec![*institution, *incumbent], Vec::new(), Vec::new()), + ResolvedOp::OpenForum { + forum, standing, .. + } => match standing { + AuthorityTarget::Subject(other) => (vec![*forum, *other], Vec::new(), Vec::new()), + AuthorityTarget::PlaceSubtree(root) => (vec![*forum], vec![*root], Vec::new()), + }, + ResolvedOp::CloseForum { .. } => (Vec::new(), Vec::new(), Vec::new()), + ResolvedOp::AcquireKnowledge { subject, .. } | ResolvedOp::Forget { subject, .. } => { + (vec![*subject], Vec::new(), Vec::new()) + } + ResolvedOp::Communicate { speaker, .. } | ResolvedOp::Display { actor: speaker, .. } => { + (vec![*speaker], Vec::new(), Vec::new()) + } + // The place is the whole ground. Confining by it is not weaker than + // confining by the recipients: `covers_place` is transitive, so every + // subject the fan-out selects stands under the place, and a place + // admitted under a root puts all of them under that root. Naming the + // recipients here would be a second statement of the same rule, + // computed from state this function does not read. + ResolvedOp::Witness { place, .. } => (Vec::new(), places(vec![*place]), Vec::new()), + ResolvedOp::SetPersonaMaterial { subject, material } => ( + std::iter::once(*subject) + .chain(material.reads.keys().copied()) + .collect(), + Vec::new(), + Vec::new(), + ), + ResolvedOp::SetReach { channel, reach } => { + let mut subjects = Vec::new(); + let mut named = Vec::new(); + match reach { + Reach::Place(place) => named.push(*place), + Reach::Subjects(members) => subjects.extend(members.iter().copied()), + } + named.push(*channel); + (subjects, places(named), Vec::new()) + } + ResolvedOp::SetController { + channel, + controller, + } => ( + controller.iter().copied().collect(), + places(vec![*channel]), + Vec::new(), + ), + // Kernel-synthesized by `action::exercise` and by nothing a patch may + // carry; it is confined by its speaker all the same. + ResolvedOp::AssertClaim { by, .. } => (vec![*by], Vec::new(), Vec::new()), + ResolvedOp::CreateCommitment { + subject, + commitment, + .. + } => ( + std::iter::once(*subject) + .chain(commitment.counterparty) + .collect(), + Vec::new(), + Vec::new(), + ), + ResolvedOp::DischargeCommitment { subject, .. } => (vec![*subject], Vec::new(), Vec::new()), + ResolvedOp::AdvancePressure { source, target, .. } + | ResolvedOp::ReducePressure { source, target, .. } + | ResolvedOp::ResolvePressure { source, target } => { + let mut subjects = vec![*target]; + let mut named = Vec::new(); + let mut routes = Vec::new(); + match source { + PressureSource::Commitment { subject, .. } | PressureSource::Subject(subject) => { + subjects.push(*subject); + } + PressureSource::Dependency(DependencyTarget::Subject(subject)) => { + subjects.push(*subject); + } + PressureSource::Dependency(DependencyTarget::Route(edge_id)) => { + routes.push(*edge_id); + } + PressureSource::Dependency(DependencyTarget::Resource(resource)) => { + named.push(*resource); + } + } + (subjects, places(named), routes) + } + // Confinement never reaches these through the ordinary ground check: + // `confine_to_ground` refuses `Retire`, `GrantAffordance`, and + // `RevokeAffordance` unconditionally for every confined author before + // this function is called for them. The subject is named here so the + // match stays total and correct if that clause is ever bypassed. + ResolvedOp::Retire { subject } + | ResolvedOp::GrantAffordance { subject, .. } + | ResolvedOp::RevokeAffordance { subject, .. } => (vec![*subject], Vec::new(), Vec::new()), + } +} + +fn require_owner(state: &WorldState, caller: &CallerId) -> Result<(), KernelError> { + if caller == &CallerId::Principal(state.owner.clone()) { + Ok(()) + } else { + Err(KernelError::Unauthorized) + } +} + +fn require_phase(state: &WorldState, expected: WorldPhase) -> Result<(), KernelError> { + if state.phase == expected { + Ok(()) + } else { + Err(KernelError::WrongPhase { + expected, + actual: state.phase, + }) + } +} + +fn normalize_title(value: &str) -> Result { + let value = value.trim(); + if value.is_empty() { + Err(KernelError::EmptyTitle) + } else { + Ok(value.to_owned()) + } +} + +fn validate_principal(value: &PrincipalId) -> Result<(), KernelError> { + if value.0.trim().is_empty() || value.0.trim() != value.0 { + Err(KernelError::EmptyPrincipal) + } else { + Ok(()) + } +} + +fn validate_assignment(value: &ControllerAssignment) -> Result<(), KernelError> { + if let ControllerAssignment::Human { principal, .. } = value { + validate_principal(principal)?; + } + Ok(()) +} + +/// The revision a non-genesis commit resolves to: one past `state.revision`, +/// which still holds the *previous* revision here, since `submit` only bumps +/// it after `apply_effect` returns. Genesis is not a caller: it resolves to +/// `state.revision` itself and computes that directly (PA.f49). +fn resolution_revision(state: &WorldState) -> Result { + state + .revision + .checked_add(1) + .ok_or_else(|| KernelError::Serialization("world revision overflow".into())) +} + +/// `command_id` is the band draw's only per-command term, so the arm that +/// re-derives an exercised decision needs the same one `reduce` drew from. +fn apply_effect( + state: &mut WorldState, + command_id: CommandId, + caller: &CallerId, + effect: &WorldEffect, +) -> Result<(), KernelError> { + // The capability rule `reduce` decided, re-decided here against the effect + // the command produced. + if let CallerId::System(capability) = caller { + let admitted = matches!( + (capability, effect), + (SystemCapability::Clock, WorldEffect::TimeAdvanced { .. }) + | (SystemCapability::Play, WorldEffect::TimeAdvanced { .. }) + | ( + SystemCapability::Elaborator { .. } + | SystemCapability::Consumer { .. } + | SystemCapability::Play, + WorldEffect::PatchAdmitted { .. } + ) + ); + if !admitted { + return Err(KernelError::Unauthorized); + } + } + match effect { + WorldEffect::WorldCreated { .. } => { + return Err(KernelError::Invariant( + "world genesis cannot be applied as a mutable effect".into(), + )); + } + WorldEffect::PatchAdmitted { answers, resolved } => { + require_answer(state, caller, answers.as_ref(), !resolved.declares_nothing())?; + require_ruler(caller, resolved).map_err(|_| { + KernelError::Invariant( + "admitted patch rules or mints without the play authority".into(), + ) + })?; + let confinement = + require_patch_author(state, caller, answers.as_ref()).map_err(|_| { + KernelError::Invariant( + "admitted patch does not satisfy admission authority".into(), + ) + })?; + if let Some(ground) = confinement { + confine_to_ground(state, resolved, ground).map_err(|_| { + KernelError::Invariant( + "admitted patch wrote outside its author's ground".into(), + ) + })?; + } + // The deficit before the write, so "strictly decreased" is a + // comparison rather than a claim the effect makes. + let before = match answers { + Some(PatchAnswer::Deficit(jurisdiction)) => { + jurisdiction_deficit(state, *jurisdiction)? + } + _ => 0, + }; + let resolves_to = resolution_revision(state)?; + admit_resolved(state, resolved, resolves_to)?; + // What makes "a commit clears exactly the boundary it answers" + // structural rather than hoped for. "Nothing else clears one" is + // true by construction: boundaries are derived and no writer + // clears one. + match answers { + Some(PatchAnswer::Boundary(answered)) => { + if exact_boundary(state, answered).is_ok() { + return Err(KernelError::AnswerNotSatisfied); + } + } + Some(PatchAnswer::Deficit(jurisdiction)) => { + if jurisdiction_deficit(state, *jurisdiction)? >= before { + return Err(KernelError::AnswerNotSatisfied); + } + } + None => {} + } + } + WorldEffect::DraftApproved { principal } => { + if state.phase != WorldPhase::Draft + || caller != &CallerId::Principal(principal.clone()) + || !required_approvers(state).contains(principal) + || !state.draft_approvals.insert(principal.clone()) + { + return Err(KernelError::Invariant( + "draft-approval effect is unauthorized or duplicate".into(), + )); + } + } + WorldEffect::WorldActivated => { + if caller != &CallerId::Principal(state.owner.clone()) + || state.phase != WorldPhase::Draft + || !required_approvers(state).is_subset(&state.draft_approvals) + { + return Err(KernelError::Invariant( + "activation does not satisfy lifecycle authority".into(), + )); + } + state.phase = WorldPhase::Active; + } + WorldEffect::DecisionExercised { + opportunity, + invocation, + event, + } => { + let current = exact_opportunity(state, opportunity)?; + let assignment = state + .controller_assignments + .get(¤t.scope) + .ok_or_else(|| { + KernelError::Invariant("decision scope lost its controller".into()) + })?; + if state.phase != WorldPhase::Active + || assignment.expected_caller().as_ref() != Some(caller) + { + return Err(KernelError::Invariant( + "decision effect does not match exact opportunity authority".into(), + )); + } + let granted = require_granted(state, ¤t, invocation.affordance)?; + // The whole event is re-derived by the function that produced the + // honest one, so a forged band, operation, magnitude, minted claim, + // or utterance is one comparison rather than a clause apiece. + let derived = action::exercise(state, command_id, ¤t, &granted, invocation)?; + if derived != *event { + return Err(KernelError::Invariant( + "decision effect does not derive from its opportunity".into(), + )); + } + state.events.push(event.clone()); + if !event.effects.is_empty() { + // `derived != *event` above already proved `event.revision` is + // exactly what `resolution_revision(state)` would compute right + // now; read it back rather than computing it a second time. + apply_operations(state, &event.effects, &[], event.revision)?; + } + state + .last_opportunity_at + .insert(current.scope.subject_id, state.now); + } + WorldEffect::DecisionDeclined { opportunity } => { + let current = exact_opportunity(state, opportunity)?; + let assignment = state + .controller_assignments + .get(¤t.scope) + .ok_or_else(|| { + KernelError::Invariant("decision scope lost its controller".into()) + })?; + if state.phase != WorldPhase::Active + || assignment.expected_caller().as_ref() != Some(caller) + { + return Err(KernelError::Invariant( + "decline effect does not match exact opportunity authority".into(), + )); + } + // A decline consumed the turn: a controller that keeps declining + // must not keep the head of the queue. + state + .last_opportunity_at + .insert(current.scope.subject_id, state.now); + } + WorldEffect::TimeAdvanced { + minutes, + to, + motion, + } => { + require_phase(state, WorldPhase::Active)?; + require_clock_caller(state, caller)?; + let derived_to = state + .now + .checked_add(*minutes) + .ok_or_else(|| KernelError::Serialization("world clock overflow".into()))?; + // The whole motion is re-derived rather than trusted field by + // field, so a forged fulfilment, magnitude, row, and target are one + // comparison. + if derived_to != *to || clock::derive_motion(state, derived_to) != *motion { + return Err(KernelError::Invariant( + "time effect does not derive from the world clock".into(), + )); + } + state.now = *to; + for rolled in &motion.fulfilled { + let commitment = state + .commitments + .get_mut(&rolled.subject) + .and_then(|held| held.get_mut(&rolled.key)) + .ok_or_else(|| { + KernelError::Invariant("a fulfilled routine has no commitment".into()) + })?; + commitment.due = rolled.next_due; + } + // No inner map is ever left empty, because `derive_motion` emits no + // zero magnitude. + for written in &motion.pressed { + state + .pressures + .entry(written.target) + .or_default() + .insert(written.source, written.magnitude); + } + } + WorldEffect::LensWeightsReplaced { weights } => { + if caller != &CallerId::Principal(state.owner.clone()) || !weights.draws() { + return Err(KernelError::Invariant( + "lens weights effect does not satisfy owner admission".into(), + )); + } + state.lens_weights = weights.clone(); + } + } + Ok(()) +} + +fn digest(value: &T) -> Result { + let bytes = rmp_serde::to_vec_named(value) + .map_err(|error| KernelError::Serialization(error.to_string()))?; + Ok(format!("sha256:{:x}", Sha256::digest(bytes))) +} + +fn state_digest(state: &WorldState) -> Result { + let mut value = state.clone(); + value.state_digest.clear(); + value.last_commit_digest = None; + digest(&value) +} + +fn commit_digest(commit: &WorldCommit) -> Result { + let mut value = commit.clone(); + value.digest.clear(); + digest(&value) +} + +#[cfg(test)] +mod tests { + use super::patch::kernel_speak_grant; + use super::*; + + /// What a committed event actually asserted, read from the one readable + /// home of an utterance: `facts[fact].statement`. The committed event's + /// own `AssertClaim` effect carries the same bytes as the replay witness, + /// but no projection reads that copy; `facts` is the surface. + pub(crate) fn spoken<'a>(state: &'a WorldState, event: &DecisionEvent) -> Option<&'a str> { + event + .speech + .and_then(|fact| state.facts.get(&fact)) + .map(|record| record.statement.as_str()) + } + + pub(crate) fn owner() -> PrincipalId { + PrincipalId::new("owner@example.test") + } + + pub(crate) fn human_principal() -> PrincipalId { + PrincipalId::new("human@example.test") + } + + pub(crate) fn auth_principal(principal: PrincipalId) -> AuthenticatedCaller { + AuthenticatedCaller::fixture(CallerId::Principal(principal)) + } + + pub(crate) fn subject( + handle: &str, + label: &str, + kind: SubjectKind, + controller: NewController, + ) -> Declaration { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind, + controller, + affordances: kernel_speak_grant(), + // The fixture world is one room. Co-located speech needs a place to + // fill, so every fixture subject stands in the commons. + position: Some(Ref::Draft(DraftHandle::new(COMMONS))), + import_key: None, + }) + } + + /// The one place the base fixture world declares. + pub(crate) const COMMONS: &str = "commons"; + + /// How many entities the base fixture world admits at genesis: the commons + /// and nothing else. A patch-lane test that proves a rejection allocated + /// nothing compares against this rather than against zero. + pub(crate) const FIXTURE_ENTITIES: usize = 1; + + /// The committed Speak entry. A post-genesis declaration grants it by + /// canonical reference, like every other structure a previous commit + /// allocated: the kernel synthesizes the entry once, at genesis. + pub(crate) fn speak_entry(kernel: &WorldKernel) -> Ref { + Ref::Existing( + *kernel + .state + .affordance_catalog + .iter() + .find(|(_, entry)| entry.kind.0 == "speak") + .map(|(affordance_id, _)| affordance_id) + .expect("genesis admits the kernel Speak entry"), + ) + } + + /// A catalog entry by kind name. An affordance id names an entry, not a + /// subject's copy of one, so a test that needs an entry a scope does not + /// hold asks for it by name rather than by list position. + pub(crate) fn affordance_named(snapshot: &WorldSnapshot, kind: &str) -> AffordanceId { + snapshot + .affordances + .iter() + .find(|entry| entry.entry.kind.0 == kind) + .map(|entry| entry.id) + .expect("the fixture world declares this affordance") + } + + /// Every stock lens at weight one. + pub(crate) fn stock_weights() -> LensWeights { + LensWeights::new(Lens::ALL.into_iter().map(|lens| (lens, 1)).collect()) + } + + pub(crate) fn creation(id: CommandId, title: &str) -> CreateWorld { + CreateWorld { + id, + owner: owner(), + title: title.into(), + brief: String::new(), + patch: WorldPatch { + operations: Vec::new(), + evidence: Vec::new(), + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(COMMONS), + label: "The Commons".into(), + kind: EntityKind::Place, + container: None, + }), + // A second, world-declared entry granted to exactly one + // subject, so the fixture world has more than one verb and + // grant sets differ between scopes. + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("convene"), + kind: AffordanceKindName("convene".into()), + roles: Vec::new(), + // A speech-carrying entry must name exactly one + // audience for the lowering to read. + preconditions: vec![Precondition::CanBroadcast { + via: AudienceSpec::Colocated, + }], + effect_slots: Vec::new(), + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + carries_speech: true, + }), + subject( + "human", + "The Human", + SubjectKind::Person, + NewController::Human { + principal: human_principal(), + }, + ), + subject( + "persona", + "The Witness", + SubjectKind::Person, + NewController::NarrativePersona, + ), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("operator"), + label: "The Council".into(), + kind: SubjectKind::Institution, + controller: NewController::OperationalAgent, + affordances: kernel_speak_grant() + .into_iter() + .chain(std::iter::once(Ref::Draft(DraftHandle::new("convene")))) + .collect(), + position: Some(Ref::Draft(DraftHandle::new(COMMONS))), + import_key: None, + }), + ], + }, + scale_intent: WorldScaleIntentRef::default(), + lens_weights: stock_weights(), + grammar: None, + } + } + + pub(crate) fn command( + snapshot: &WorldSnapshot, + id: CommandId, + caller: CallerId, + body: CommandBody, + ) -> CommandEnvelope { + CommandEnvelope { + id, + world_id: snapshot.world_id, + expected_revision: snapshot.revision, + caller, + body, + } + } + + pub(crate) fn submit_owner( + kernel: &mut WorldKernel, + snapshot: &WorldSnapshot, + body: CommandBody, + ) -> SubmitReceipt { + kernel + .submit( + command( + snapshot, + CommandId::new(), + CallerId::Principal(owner()), + body, + ), + &auth_principal(owner()), + ) + .unwrap() + } + + pub(crate) fn activate(kernel: &mut WorldKernel) -> WorldSnapshot { + let genesis = kernel.snapshot().unwrap(); + submit_owner(kernel, &genesis, CommandBody::ApproveDraft); + let after_owner = kernel.snapshot().unwrap(); + kernel + .submit( + command( + &after_owner, + CommandId::new(), + CallerId::Principal(human_principal()), + CommandBody::ApproveDraft, + ), + &auth_principal(human_principal()), + ) + .unwrap(); + let approved = kernel.snapshot().unwrap(); + submit_owner(kernel, &approved, CommandBody::ActivateWorld); + kernel.snapshot().unwrap() + } + + /// The canonical IDs of the shared topology fixture: three places, four + /// routes with every access and open combination the operations read, and one + /// subject standing in the yard. + pub(crate) struct Topology { + pub(crate) yard: EntityId, + pub(crate) road: EntityId, + pub(crate) gate: EntityId, + pub(crate) ramp: EdgeId, + pub(crate) shutter: EdgeId, + pub(crate) toll: EdgeId, + pub(crate) span: EdgeId, + pub(crate) walker: SubjectId, + } + + fn place(handle: &str, label: &str) -> Declaration { + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: EntityKind::Place, + container: None, + }) + } + + fn way( + handle: &str, + label: &str, + from: &str, + to: &str, + access: AccessKind, + cost: u32, + ) -> Declaration { + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + from: Ref::Draft(DraftHandle::new(from)), + to: Ref::Draft(DraftHandle::new(to)), + access, + cost: Cost(cost), + }) + } + + pub(crate) fn topology_patch(speak: Ref) -> WorldPatch { + WorldPatch { + declarations: vec![ + place("yard", "The Cavity Yard"), + place("road", "The Rhythm Road"), + place("gate", "The Rain Gate"), + way( + "ramp", + "The Yard Ramp", + "yard", + "road", + AccessKind::Public, + 12, + ), + way( + "shutter", + "The Yard Shutter", + "yard", + "gate", + AccessKind::Public, + 5, + ), + way( + "toll", + "The Toll Stair", + "yard", + "gate", + AccessKind::Restricted { + requires: AuthorityKindName(ADMIT_KIND.into()), + }, + 4, + ), + way( + "span", + "The Western Span", + "road", + "gate", + AccessKind::Public, + 7, + ), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("walker"), + label: "The Walker".into(), + kind: SubjectKind::Person, + controller: NewController::OperationalAgent, + affordances: BTreeSet::from([speak]), + position: Some(Ref::Draft(DraftHandle::new("yard"))), + import_key: None, + }), + ], + // A route that should start closed is declared and closed in one + // patch, so `open` keeps a single writer family. + operations: vec![ComponentOp::CloseRoute { + route: Ref::Draft(DraftHandle::new("shutter")), + }], + evidence: Vec::new(), + } + } + + pub(crate) fn admit_topology(kernel: &mut WorldKernel) -> Topology { + let before = kernel.snapshot().unwrap(); + let receipt = submit_owner( + kernel, + &before, + CommandBody::AdmitPatch { + answers: None, + patch: topology_patch(speak_entry(kernel)), + }, + ); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + let entity = |label: &str| { + *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == label) + .expect("a declared place") + .0 + }; + let edge = |label: &str| { + *kernel + .state + .edges + .iter() + .find(|(_, record)| record.label() == label) + .expect("a declared route") + .0 + }; + Topology { + yard: entity("The Cavity Yard"), + road: entity("The Rhythm Road"), + gate: entity("The Rain Gate"), + ramp: edge("The Yard Ramp"), + shutter: edge("The Yard Shutter"), + toll: edge("The Toll Stair"), + span: edge("The Western Span"), + walker: *kernel + .state + .subjects + .iter() + .find(|(_, subject)| subject.label == "The Walker") + .expect("the walker is admitted") + .0, + } + } + + /// The canonical IDs of the custody fixture: two resources and two holder + /// subjects standing in the topology, with the first holder carrying an + /// evidenced opening balance. + pub(crate) struct Custody { + pub(crate) tithe: EntityId, + pub(crate) ingot: EntityId, + pub(crate) holder: SubjectId, + pub(crate) counterparty: SubjectId, + } + + /// The seed world's authority kinds, offices, and grievance. They are world + /// data: the kernel compares these strings and reads them no other way. + pub(crate) const LEVY_KIND: &str = "levy"; + pub(crate) const ADMIT_KIND: &str = "admit"; + pub(crate) const COMMAND_KIND: &str = "command"; + pub(crate) const JUDGE_KIND: &str = "judge"; + pub(crate) const WARDEN_OFFICE: &str = "warden"; + pub(crate) const BAILIFF_OFFICE: &str = "bailiff"; + pub(crate) const SEIZURE_GRIEVANCE: &str = "seizure"; + + pub(crate) const TITHE_RECEIPT: &str = "receipt:rhythm-tithe-census"; + pub(crate) const OPENING_BALANCE: u64 = 7; + + pub(crate) fn resource(handle: &str, label: &str) -> Declaration { + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: EntityKind::Resource, + container: None, + }) + } + + fn holder(handle: &str, label: &str, place: EntityId, speak: Ref) -> Declaration { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: SubjectKind::Institution, + controller: NewController::OperationalAgent, + affordances: std::iter::once(speak) + .chain(carry_affordances().into_iter().map(|declaration| { + let Declaration::Affordance(entry) = declaration else { + unreachable!("carry_affordances declares only affordances") + }; + Ref::Draft(entry.handle) + })) + .collect(), + position: Some(Ref::Existing(place)), + import_key: None, + }) + } + + pub(crate) const CARRY_HANDLE: &str = "carry"; + + /// The worked affordances for the action lane. Every one carries the same + /// four roles and the same bounded `Transfer` slot, so a test varies exactly + /// one thing — a precondition or a band table — by naming a different entry + /// rather than by reaching into a committed catalog. The catalog is + /// Draft-only, so authoring it is how a world gets a verb. + fn carry_roles() -> Vec { + vec![ + RoleSpec { + role: Role("from".into()), + kind: RefKind::Subject(None), + }, + RoleSpec { + role: Role("recipient".into()), + kind: RefKind::Subject(None), + }, + RoleSpec { + role: Role("place".into()), + kind: RefKind::Entity(EntityKind::Place), + }, + RoleSpec { + role: Role("resource".into()), + kind: RefKind::Entity(EntityKind::Resource), + }, + ] + } + + /// Two slots on disjoint bands: band 0 names only the transfer, band 1 only + /// the consume. Both slots are proposed on every invocation, so the entry + /// separates what a proposer offered from what a draw admitted. + fn split_variant() -> Declaration { + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("carry-split"), + kind: AffordanceKindName("carry_split".into()), + roles: carry_roles(), + preconditions: Vec::new(), + effect_slots: vec![ + EffectSlot { + op_kind: ComponentOpKind::Transfer, + roles: vec![ + Role("from".into()), + Role("recipient".into()), + Role("resource".into()), + ], + bounds: Bounds::Quantity(Quantity(3)), + }, + EffectSlot { + op_kind: ComponentOpKind::Consume, + roles: vec![Role("from".into()), Role("resource".into())], + bounds: Bounds::Quantity(Quantity(3)), + }, + ], + outcome_bands: vec![ + OutcomeBand { + weight: 1, + effects: vec![0], + }, + OutcomeBand { + weight: 1, + effects: vec![1], + }, + ], + carries_speech: false, + }) + } + + fn carry_variant( + handle: &str, + kind: &str, + preconditions: Vec, + outcome_bands: Vec, + ) -> Declaration { + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new(handle), + kind: AffordanceKindName(kind.into()), + roles: carry_roles(), + preconditions, + effect_slots: vec![EffectSlot { + op_kind: ComponentOpKind::Transfer, + roles: vec![ + Role("from".into()), + Role("recipient".into()), + Role("resource".into()), + ], + bounds: Bounds::Quantity(Quantity(3)), + }], + outcome_bands, + carries_speech: false, + }) + } + + fn certain_band() -> Vec { + vec![OutcomeBand { + weight: 1, + effects: vec![0], + }] + } + + fn place_role() -> Role { + Role("place".into()) + } + + /// Carry, and five variants that each move one dial: a holding demand above + /// the opening balance, a reach budget short of the two-hop path, one that + /// covers it, a band that names no effect, and three equally weighted bands. + pub(crate) fn carry_affordances() -> Vec { + vec![ + carry_variant( + CARRY_HANDLE, + "carry", + vec![ + Precondition::Present { at: place_role() }, + Precondition::Holds { + resource: Role("resource".into()), + at_least: Quantity(1), + }, + ], + certain_band(), + ), + carry_variant( + "carry-greedy", + "carry_greedy", + vec![ + Precondition::Present { at: place_role() }, + Precondition::Holds { + resource: Role("resource".into()), + at_least: Quantity(OPENING_BALANCE + 1), + }, + ], + certain_band(), + ), + carry_variant( + "carry-holds", + "carry_holds", + vec![Precondition::Holds { + resource: Role("resource".into()), + at_least: Quantity(1), + }], + certain_band(), + ), + carry_variant( + "carry-near", + "carry_near", + vec![Precondition::Reachable { + to: place_role(), + within: Cost(NEAR_REACH), + }], + certain_band(), + ), + carry_variant( + "carry-far", + "carry_far", + vec![Precondition::Reachable { + to: place_role(), + within: Cost(FAR_REACH), + }], + certain_band(), + ), + carry_variant( + "carry-idle", + "carry_idle", + Vec::new(), + vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + ), + carry_variant( + "carry-chance", + "carry_chance", + Vec::new(), + vec![ + OutcomeBand { + weight: 1, + effects: vec![0], + }, + OutcomeBand { + weight: 1, + effects: Vec::new(), + }, + OutcomeBand { + weight: 1, + effects: Vec::new(), + }, + ], + ), + split_variant(), + ] + } + + /// Yard to gate over the open shutter alone. + pub(crate) const NEAR_REACH: u32 = 5; + /// Yard to gate over the ramp and the span, which is the only open public + /// path while the shutter is closed. + pub(crate) const FAR_REACH: u32 = 19; + + /// Declarations and evidence are Draft-only, so the resources, the holders, + /// and the one evidenced `Admit` that creates the opening balance all land + /// before activation. There is no holdings declaration field: quantity is + /// created by `Admit` and by nothing else, in this lane as in every other. + pub(crate) fn custody_patch(topology: &Topology, speak: Ref) -> WorldPatch { + WorldPatch { + declarations: carry_affordances() + .into_iter() + .chain([ + resource("tithe", "The Rhythm Tithe"), + resource("ingot", "The Cut Ingot"), + holder("clerk", "The Ledger Clerk", topology.yard, speak.clone()), + holder("keeper", "The Gate Keeper", topology.gate, speak), + ]) + .collect(), + operations: vec![ComponentOp::Admit { + holder: Ref::Draft(DraftHandle::new("clerk")), + resource: Ref::Draft(DraftHandle::new("tithe")), + qty: Quantity(OPENING_BALANCE), + evidence: EvidenceRef::new(TITHE_RECEIPT), + }], + evidence: vec![EvidenceRef::new(TITHE_RECEIPT)], + } + } + + pub(crate) fn admit_custody(kernel: &mut WorldKernel, topology: &Topology) -> Custody { + let before = kernel.snapshot().unwrap(); + let receipt = submit_owner( + kernel, + &before, + CommandBody::AdmitPatch { + answers: None, + patch: custody_patch(topology, speak_entry(kernel)), + }, + ); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + let entity = |label: &str| { + *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == label) + .expect("a declared resource") + .0 + }; + let subject = |label: &str| { + *kernel + .state + .subjects + .iter() + .find(|(_, record)| record.label == label) + .expect("a declared holder") + .0 + }; + Custody { + tithe: entity("The Rhythm Tithe"), + ingot: entity("The Cut Ingot"), + holder: subject("The Ledger Clerk"), + counterparty: subject("The Gate Keeper"), + } + } + + /// Topology, custody, then activation: everything a custody test needs, in + /// the one order the phase rules allow. + pub(crate) fn custody_world(kernel: &mut WorldKernel) -> (Topology, Custody, WorldSnapshot) { + let topology = admit_topology(kernel); + let custody = admit_custody(kernel, &topology); + let active = activate(kernel); + (topology, custody, active) + } + + /// The canonical IDs of the civic fixture: a hall containing a chamber, an + /// institution holding jurisdiction over the hall, a person who holds that + /// jurisdiction only through an office, a person and a resource inside the + /// hall, and a person standing outside it. + pub(crate) struct Civic { + pub(crate) hall: EntityId, + pub(crate) chamber: EntityId, + pub(crate) passage: EdgeId, + pub(crate) causeway: EdgeId, + pub(crate) postern: EdgeId, + pub(crate) treasury: SubjectId, + pub(crate) reeve: SubjectId, + pub(crate) farmer: SubjectId, + pub(crate) outsider: SubjectId, + pub(crate) grain: EntityId, + } + + pub(crate) fn authority_kind(name: &str) -> AuthorityKindName { + AuthorityKindName(name.into()) + } + + pub(crate) fn office(name: &str) -> OfficeName { + OfficeName(name.into()) + } + + pub(crate) fn grievance(name: &str) -> GrievanceKindName { + GrievanceKindName(name.into()) + } + + pub(crate) fn over_place(place: EntityId) -> AuthorityTargetRef { + AuthorityTargetRef::PlaceSubtree(Ref::Existing(place)) + } + + pub(crate) fn over_subject(subject_id: SubjectId) -> AuthorityTargetRef { + AuthorityTargetRef::Subject(Ref::Existing(subject_id)) + } + + pub(crate) fn grant_of(kind: &str, over: AuthorityTargetRef) -> AuthorityGrantRef { + AuthorityGrantRef { + kind: authority_kind(kind), + over, + } + } + + pub(crate) fn grant_to(holder: SubjectId, kind: &str, over: AuthorityTargetRef) -> ComponentOp { + ComponentOp::GrantAuthority { + holder: Ref::Existing(holder), + grant: grant_of(kind, over), + } + } + + /// Seven world-authored civic entries. The kernel builds none of them; + /// each is a worked example of what a seed author writes to make the + /// political layer playable rather than administratively imposed. + fn civic_affordances() -> Vec { + let entry = |handle: &str, + kind: &str, + roles: Vec, + preconditions: Vec, + effect_slots: Vec, + outcome_bands: Vec, + carries_speech: bool| { + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new(handle), + kind: AffordanceKindName(kind.into()), + roles, + preconditions, + effect_slots, + outcome_bands, + carries_speech, + }) + }; + let role = |name: &str, kind: RefKind| RoleSpec { + role: Role(name.into()), + kind, + }; + let slot = |op_kind: ComponentOpKind, roles: Vec<&str>, bounds: Bounds| EffectSlot { + op_kind, + roles: roles.into_iter().map(|name| Role(name.into())).collect(), + bounds, + }; + let authorized = |over: &str, kind: &str| Precondition::Authorized { + over: Role(over.into()), + kind: authority_kind(kind), + }; + vec![ + // The payee is the reserved `actor` role, so an authorized + // collector cannot lawfully take a tax and send it to a friend. + entry( + "levy", + "levy", + vec![ + role("payer", RefKind::Subject(None)), + role("resource", RefKind::Entity(EntityKind::Resource)), + ], + vec![authorized("payer", LEVY_KIND)], + vec![slot( + ComponentOpKind::Transfer, + vec!["payer", "actor", "resource"], + Bounds::Quantity(Quantity(10)), + )], + certain_band(), + false, + ), + entry( + "delegate", + "delegate", + vec![ + role("deputy", RefKind::Subject(None)), + role("ground", RefKind::Entity(EntityKind::Place)), + ], + // The precondition names one kind and the slot grants another, + // so the monotonicity rule is the check that decides whether + // the granted authority is one the granter holds. + vec![authorized("ground", COMMAND_KIND)], + vec![slot( + ComponentOpKind::GrantAuthority { + kind: authority_kind(LEVY_KIND), + }, + vec!["deputy", "ground"], + Bounds::None, + )], + certain_band(), + false, + ), + // Isolates the action-lane's revocation envelope: no separate + // precondition, so a rejection here can only be + // `DelegationNotMonotone`. + entry( + "revoke", + "revoke", + vec![ + role("holder", RefKind::Subject(None)), + role("ground", RefKind::Entity(EntityKind::Place)), + ], + Vec::new(), + vec![slot( + ComponentOpKind::RevokeAuthority { + kind: authority_kind(LEVY_KIND), + }, + vec!["holder", "ground"], + Bounds::None, + )], + certain_band(), + false, + ), + entry( + "deploy", + "deploy", + vec![ + role("subordinate", RefKind::Subject(None)), + role("via", RefKind::Edge(patch::EdgeKind::Route)), + ], + vec![authorized("subordinate", COMMAND_KIND)], + vec![slot( + ComponentOpKind::Relocate, + vec!["subordinate", "via"], + Bounds::None, + )], + certain_band(), + false, + ), + // The first affordance whose effect changes shared topology under a + // legitimacy check; the second band is the interdiction that fails. + entry( + "sanction", + "sanction", + vec![role("road", RefKind::Edge(patch::EdgeKind::Route))], + vec![authorized("road", COMMAND_KIND)], + vec![slot( + ComponentOpKind::CloseRoute, + vec!["road"], + Bounds::None, + )], + vec![ + OutcomeBand { + weight: 3, + effects: vec![0], + }, + OutcomeBand { + weight: 1, + effects: Vec::new(), + }, + ], + false, + ), + // Succession is an act someone performs under authority, not a + // declared method string. + entry( + "appoint", + "appoint", + vec![ + role("institution", RefKind::Subject(None)), + role("candidate", RefKind::Subject(None)), + ], + vec![authorized("institution", COMMAND_KIND)], + vec![slot( + ComponentOpKind::InstallIncumbent { + office: office(BAILIFF_OFFICE), + }, + vec!["institution", "candidate"], + Bounds::None, + )], + certain_band(), + false, + ), + // The reader that keeps `Redress` from being decorative. + entry( + "petition", + "petition", + Vec::new(), + vec![ + Precondition::HasStanding { + grievance: grievance(SEIZURE_GRIEVANCE), + }, + // A petition is spoken, so the entry names where it lands. + Precondition::CanBroadcast { + via: AudienceSpec::Colocated, + }, + ], + Vec::new(), + vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + true, + ), + ] + } + + fn civic_grants(handles: &[&str], speak: &Ref) -> BTreeSet> { + std::iter::once(speak.clone()) + .chain( + handles + .iter() + .map(|handle| Ref::Draft(DraftHandle::new(*handle))), + ) + .collect() + } + + pub(crate) fn civic_patch(topology: &Topology, speak: Ref) -> WorldPatch { + let person = |handle: &str, label: &str, place: Ref, handles: &[&str]| { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: SubjectKind::Person, + controller: NewController::OperationalAgent, + affordances: civic_grants(handles, &speak), + position: Some(place), + import_key: None, + }) + }; + let declarations = civic_affordances() + .into_iter() + .chain([ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("hall"), + label: "The Tithe Hall".into(), + kind: EntityKind::Place, + container: None, + }), + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("chamber"), + label: "The Counting Chamber".into(), + kind: EntityKind::Place, + container: Some(Ref::Draft(DraftHandle::new("hall"))), + }), + resource("grain", "The Winter Grain"), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("passage"), + label: "The Hall Passage".into(), + from: Ref::Draft(DraftHandle::new("chamber")), + to: Ref::Draft(DraftHandle::new("hall")), + access: AccessKind::Public, + cost: Cost(3), + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("causeway"), + label: "The Hall Causeway".into(), + from: Ref::Draft(DraftHandle::new("hall")), + to: Ref::Existing(topology.road), + access: AccessKind::Public, + cost: Cost(6), + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("postern"), + label: "The Hall Postern".into(), + from: Ref::Existing(topology.yard), + to: Ref::Draft(DraftHandle::new("chamber")), + access: AccessKind::Restricted { + requires: authority_kind(ADMIT_KIND), + }, + cost: Cost(2), + }), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("treasury"), + label: "The Tithe Treasury".into(), + kind: SubjectKind::Institution, + controller: NewController::OperationalAgent, + affordances: civic_grants( + &[ + "levy", "delegate", "deploy", "sanction", "appoint", "revoke", + ], + &speak, + ), + position: Some(Ref::Draft(DraftHandle::new("hall"))), + import_key: None, + }), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("reeve"), + label: "The Hall Reeve".into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + affordances: civic_grants( + &["levy", "delegate", "petition", "sanction"], + &speak, + ), + position: Some(Ref::Draft(DraftHandle::new("chamber"))), + import_key: None, + }), + person( + "farmer", + "The Winter Farmer", + Ref::Draft(DraftHandle::new("chamber")), + &["levy", "petition", "revoke"], + ), + person( + "outsider", + "The Road Pedlar", + Ref::Existing(topology.road), + &["levy", "petition"], + ), + // Deliberately unplaced: a place-subtree jurisdiction covers a + // subject through its position, so a subject with none is + // covered by nothing. + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("nowhere"), + label: "The Unhoused".into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + affordances: civic_grants(&["levy", "petition"], &speak), + position: None, + import_key: None, + }), + ]) + .collect(); + WorldPatch { + declarations, + operations: vec![ + ComponentOp::Admit { + holder: Ref::Draft(DraftHandle::new("farmer")), + resource: Ref::Draft(DraftHandle::new("grain")), + qty: Quantity(OPENING_BALANCE), + evidence: EvidenceRef::new(TITHE_RECEIPT), + }, + ComponentOp::Admit { + holder: Ref::Draft(DraftHandle::new("outsider")), + resource: Ref::Draft(DraftHandle::new("grain")), + qty: Quantity(OPENING_BALANCE), + evidence: EvidenceRef::new(TITHE_RECEIPT), + }, + ComponentOp::GrantAuthority { + holder: Ref::Draft(DraftHandle::new("treasury")), + grant: AuthorityGrantRef { + kind: authority_kind(LEVY_KIND), + over: AuthorityTargetRef::PlaceSubtree(Ref::Draft(DraftHandle::new( + "hall", + ))), + }, + }, + ComponentOp::GrantAuthority { + holder: Ref::Draft(DraftHandle::new("treasury")), + grant: AuthorityGrantRef { + kind: authority_kind(COMMAND_KIND), + over: AuthorityTargetRef::PlaceSubtree(Ref::Draft(DraftHandle::new( + "hall", + ))), + }, + }, + ComponentOp::OpenOffice { + institution: Ref::Draft(DraftHandle::new("treasury")), + office: office(WARDEN_OFFICE), + delegated: BTreeSet::from([authority_kind(LEVY_KIND)]), + }, + ComponentOp::OpenOffice { + institution: Ref::Draft(DraftHandle::new("treasury")), + office: office(BAILIFF_OFFICE), + delegated: BTreeSet::from([authority_kind(JUDGE_KIND)]), + }, + ComponentOp::InstallIncumbent { + institution: Ref::Draft(DraftHandle::new("treasury")), + office: office(WARDEN_OFFICE), + incumbent: Ref::Draft(DraftHandle::new("reeve")), + }, + ComponentOp::OpenForum { + grievance: grievance(SEIZURE_GRIEVANCE), + forum: Ref::Draft(DraftHandle::new("treasury")), + standing: AuthorityTargetRef::PlaceSubtree(Ref::Draft(DraftHandle::new( + "chamber", + ))), + }, + ], + evidence: vec![EvidenceRef::new(TITHE_RECEIPT)], + } + } + + pub(crate) fn admit_civic(kernel: &mut WorldKernel, topology: &Topology) -> Civic { + let before = kernel.snapshot().unwrap(); + let receipt = submit_owner( + kernel, + &before, + CommandBody::AdmitPatch { + answers: None, + patch: civic_patch(topology, speak_entry(kernel)), + }, + ); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + let entity = |label: &str| { + *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == label) + .expect("a declared entity") + .0 + }; + let edge = |label: &str| { + *kernel + .state + .edges + .iter() + .find(|(_, record)| record.label() == label) + .expect("a declared route") + .0 + }; + let subject = |label: &str| { + *kernel + .state + .subjects + .iter() + .find(|(_, record)| record.label == label) + .expect("a declared subject") + .0 + }; + Civic { + hall: entity("The Tithe Hall"), + chamber: entity("The Counting Chamber"), + grain: entity("The Winter Grain"), + passage: edge("The Hall Passage"), + causeway: edge("The Hall Causeway"), + postern: edge("The Hall Postern"), + treasury: subject("The Tithe Treasury"), + reeve: subject("The Hall Reeve"), + farmer: subject("The Winter Farmer"), + outsider: subject("The Road Pedlar"), + } + } + + /// Topology, the civic subgraph, then activation. + pub(crate) fn civic_world(kernel: &mut WorldKernel) -> (Topology, Civic, WorldSnapshot) { + let topology = admit_topology(kernel); + let civic = admit_civic(kernel, &topology); + let active = activate(kernel); + (topology, civic, active) + } + + /// The speech bench: a hall containing a yard, a speaker and a listener in + /// the hall, a bystander in the yard, a stranger nowhere, one evidenced + /// canonical fact, and a horn that carries over the hall subtree. + pub(crate) struct Speech { + pub(crate) hall: EntityId, + pub(crate) yard: EntityId, + pub(crate) speaker: SubjectId, + pub(crate) listener: SubjectId, + pub(crate) bystander: SubjectId, + pub(crate) stranger: SubjectId, + pub(crate) flood: EntityId, + pub(crate) horn: EntityId, + pub(crate) whisper: AffordanceId, + pub(crate) proclaim: AffordanceId, + pub(crate) recant: AffordanceId, + pub(crate) stair: EdgeId, + } + + pub(crate) const FLOOD_STATEMENT: &str = "The lower hinge is flooding."; + pub(crate) const FLOOD_EVIDENCE: &str = "vault:flood-survey"; + + /// A world with one room inside another, four subjects, a fact, and a + /// channel. Two world-declared speaking entries exercise both audiences: an + /// addressed co-located `whisper` and a channel-bound `proclaim`. + pub(crate) fn speech_world(kernel: &mut WorldKernel) -> (Speech, WorldSnapshot) { + let before = kernel.snapshot().unwrap(); + let speak = speak_entry(kernel); + let person = |handle: &str, label: &str, place: Option<&str>| { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + affordances: BTreeSet::from([ + speak.clone(), + Ref::Draft(DraftHandle::new("whisper")), + Ref::Draft(DraftHandle::new("proclaim")), + Ref::Draft(DraftHandle::new("recant")), + ]), + position: place.map(|place| Ref::Draft(DraftHandle::new(place))), + import_key: None, + }) + }; + submit_owner( + kernel, + &before, + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + evidence: vec![EvidenceRef::new(FLOOD_EVIDENCE)], + operations: Vec::new(), + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("hall"), + label: "The Long Hall".into(), + kind: EntityKind::Place, + container: None, + }), + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("yard"), + label: "The Cavity Yard".into(), + kind: EntityKind::Place, + container: Some(Ref::Draft(DraftHandle::new("hall"))), + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("stair"), + label: "The Yard Stair".into(), + from: Ref::Draft(DraftHandle::new("yard")), + to: Ref::Draft(DraftHandle::new("hall")), + access: AccessKind::Public, + cost: Cost(1), + }), + Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("flood"), + label: "the flooding of the lower hinge".into(), + statement: Statement::new(FLOOD_STATEMENT).unwrap(), + standing: FactStandingRef::Canonical { + evidence: EvidenceRef::new(FLOOD_EVIDENCE), + }, + }), + // Addressed speech: the audience is still the room. + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("whisper"), + kind: AffordanceKindName("whisper".into()), + roles: vec![RoleSpec { + role: Role("target".into()), + kind: RefKind::Subject(None), + }], + preconditions: vec![Precondition::CanReach { + subject: Role("target".into()), + via: AudienceSpec::Colocated, + }], + effect_slots: Vec::new(), + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + carries_speech: true, + }), + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("proclaim"), + kind: AffordanceKindName("proclaim".into()), + roles: vec![RoleSpec { + role: Role("channel".into()), + kind: RefKind::Entity(EntityKind::Channel), + }], + preconditions: vec![Precondition::CanBroadcast { + via: AudienceSpec::Channel(Role("channel".into())), + }], + effect_slots: Vec::new(), + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + carries_speech: true, + }), + // `Knows` plus the one knowledge operation an affordance + // may propose: a subject may only unremember what it + // holds with certainty. + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("recant"), + kind: AffordanceKindName("recant".into()), + roles: vec![RoleSpec { + role: Role("fact".into()), + kind: RefKind::Entity(EntityKind::Fact), + }], + preconditions: vec![Precondition::Knows { + fact: Role("fact".into()), + at_least: Confidence::Certain, + }], + effect_slots: vec![EffectSlot { + op_kind: ComponentOpKind::Forget, + roles: vec![Role("actor".into()), Role("fact".into())], + bounds: Bounds::None, + }], + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: vec![0], + }], + carries_speech: false, + }), + person("speaker", "The Hall Speaker", Some("hall")), + person("listener", "The Hall Listener", Some("hall")), + person("bystander", "The Yard Bystander", Some("yard")), + person("stranger", "The Placeless Stranger", None), + Declaration::Channel(ChannelDeclaration { + handle: DraftHandle::new("horn"), + label: "The Temple Horn".into(), + reach: ReachRef::Place(Ref::Draft(DraftHandle::new("hall"))), + controller: Some(Ref::Draft(DraftHandle::new("speaker"))), + }), + ], + }, + }, + ); + let active = activate(kernel); + let place = |label: &str| { + active + .places + .iter() + .find(|place| place.label == label) + .expect("the declared place") + .id + }; + let who = |label: &str| { + active + .subjects + .iter() + .find(|subject| subject.label == label) + .expect("the declared subject") + .id + }; + let fact = *kernel + .state + .facts + .iter() + .find(|(_, record)| record.statement.as_str() == FLOOD_STATEMENT) + .expect("the declared fact") + .0; + let horn = *kernel + .state + .channels + .keys() + .next() + .expect("the declared channel"); + ( + Speech { + hall: place("The Long Hall"), + yard: place("The Cavity Yard"), + speaker: who("The Hall Speaker"), + listener: who("The Hall Listener"), + bystander: who("The Yard Bystander"), + stranger: who("The Placeless Stranger"), + flood: fact, + horn, + whisper: affordance_named(&active, "whisper"), + proclaim: affordance_named(&active, "proclaim"), + recant: affordance_named(&active, "recant"), + stair: active.routes[0].id, + }, + active, + ) + } + + /// Submits as owner and returns the complete mismatch set. + pub(crate) fn reject_owner( + kernel: &mut WorldKernel, + snapshot: &WorldSnapshot, + body: CommandBody, + ) -> Vec { + let error = kernel + .submit( + command( + snapshot, + CommandId::new(), + CallerId::Principal(owner()), + body, + ), + &auth_principal(owner()), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch, got {error:?}"); + }; + mismatches + } + + pub(crate) fn operations(operations: Vec) -> CommandBody { + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations, + evidence: Vec::new(), + }, + } + } + + pub(crate) fn opportunity_for( + snapshot: &WorldSnapshot, + subject_id: SubjectId, + ) -> DecisionOpportunity { + snapshot + .opportunities + .iter() + .find(|value| value.scope.subject_id == subject_id) + .expect("the subject has an opportunity") + .clone() + } + + fn opportunity(snapshot: &WorldSnapshot, mode: ControllerMode) -> DecisionOpportunity { + snapshot + .opportunities + .iter() + .find(|value| value.controller_mode == mode) + .unwrap() + .clone() + } + + fn speak(opportunity: &DecisionOpportunity, text: &str) -> DecisionInvocation { + DecisionInvocation { + affordance: opportunity.affordance_ids[0], + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Statement::new(text).unwrap()), + display: None, + } + } + + #[test] + fn external_opportunities_reject_nested_authority_claims() { + let opportunity = DecisionOpportunity { + world_id: WorldId::issue(), + revision: 4, + scope_digest: ScopeDigest::fixture("sha256:fixture"), + scope: DecisionScope { + subject_id: SubjectId::issue(), + }, + controller_id: ControllerId::issue(), + controller_mode: ControllerMode::NarrativePersona, + affordance_ids: vec![AffordanceId::issue()], + }; + let mut nested = serde_json::to_value(&opportunity).unwrap(); + nested["scope"]["caller"] = serde_json::json!("legacy-owner"); + assert!(serde_json::from_value::(nested).is_err()); + + let mut outer = serde_json::to_value(&opportunity).unwrap(); + outer["callerId"] = serde_json::json!("legacy-controller"); + assert!(serde_json::from_value::(outer).is_err()); + } + + /// A commit elsewhere in the world does not discard a bound proposal: the + /// binding is the scope digest, and this scope did not change. + #[test] + fn an_unchanged_scope_commits_at_a_later_revision() { + let dir = tempfile::tempdir().unwrap(); + let (mut kernel, _) = WorldKernel::create( + dir.path().join("world.cc"), + creation(CommandId::new(), "Unchanged"), + &auth_principal(owner()), + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + let active = activate(&mut kernel); + let bound = opportunity_for(&active, topology.walker); + + let persona = opportunity(&active, ControllerMode::NarrativePersona); + let persona_caller = CallerId::Controller(persona.controller_id); + kernel + .submit( + command( + &active, + CommandId::new(), + persona_caller.clone(), + CommandBody::ExerciseDecision { + invocation: speak(&persona, "The yard is quiet."), + opportunity: persona, + }, + ), + &AuthenticatedCaller::fixture(persona_caller), + ) + .unwrap(); + let later = kernel.snapshot().unwrap(); + assert_eq!(later.revision, active.revision + 1); + + let walker_caller = CallerId::Controller(bound.controller_id); + let receipt = kernel + .submit( + command( + &later, + CommandId::new(), + walker_caller.clone(), + CommandBody::ExerciseDecision { + invocation: speak(&bound, "I take the ramp."), + opportunity: bound.clone(), + }, + ), + &AuthenticatedCaller::fixture(walker_caller), + ) + .unwrap(); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + let after = kernel.state.events.clone(); + assert_eq!(after.len(), 2); + assert_eq!(after[1].revision, bound.revision + 2); + } + + /// Closing a route incident to the subject's place changes exactly what the + /// proposal's verification reads, so the bound proposal dies at the digest. + #[test] + fn a_changed_scope_is_rejected_with_scope_changed() { + let dir = tempfile::tempdir().unwrap(); + let (mut kernel, _) = WorldKernel::create( + dir.path().join("world.cc"), + creation(CommandId::new(), "Changed"), + &auth_principal(owner()), + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + let active = activate(&mut kernel); + let bound = opportunity_for(&active, topology.walker); + + submit_owner( + &mut kernel, + &active, + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::CloseRoute { + route: Ref::Existing(topology.ramp), + }], + evidence: Vec::new(), + }, + }, + ); + let closed = kernel.snapshot().unwrap(); + let walker_caller = CallerId::Controller(bound.controller_id); + let error = kernel + .submit( + command( + &closed, + CommandId::new(), + walker_caller.clone(), + CommandBody::ExerciseDecision { + invocation: speak(&bound, "I take the ramp."), + opportunity: bound.clone(), + }, + ), + &AuthenticatedCaller::fixture(walker_caller), + ) + .unwrap_err(); + let KernelError::ScopeChanged { + scope, + expected, + actual, + } = error + else { + panic!("expected a changed scope"); + }; + assert_eq!(scope, bound.scope); + assert_eq!(expected, bound.scope_digest); + assert_ne!(expected, actual); + assert_eq!(kernel.snapshot().unwrap(), closed); + } + + /// The digest covers the scope's controller, its grants, its Position, and + /// its incident routes, and nothing else in the world. + #[test] + fn scope_digest_reads_exactly_its_components() { + let dir = tempfile::tempdir().unwrap(); + let (mut kernel, _) = WorldKernel::create( + dir.path().join("world.cc"), + creation(CommandId::new(), "Components"), + &auth_principal(owner()), + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + activate(&mut kernel); + let scope = DecisionScope { + subject_id: topology.walker, + }; + let base = scope_digest(&kernel.state, scope).unwrap(); + + let mut changed_controller = kernel.state.clone(); + let assignment = changed_controller + .controller_assignments + .get_mut(&scope) + .unwrap(); + *assignment = ControllerAssignment::NarrativePersona { + controller_id: assignment.id().expect("the fixture scope has a controller"), + }; + assert_ne!(scope_digest(&changed_controller, scope).unwrap(), base); + + let mut changed_grants = kernel.state.clone(); + let extra = AffordanceId::issue(); + changed_grants + .affordance_catalog + .insert(extra, patch::kernel_speak_entry()); + changed_grants + .affordance_grants + .entry(scope) + .or_default() + .insert(extra); + assert_ne!(scope_digest(&changed_grants, scope).unwrap(), base); + + // The digest reads the granted entries' definitions, not only their + // ids: admission reads preconditions and ceilings, so altering an entry + // must move the digest. + let mut changed_entry = kernel.state.clone(); + let granted = *kernel.state.affordance_grants[&scope].first().unwrap(); + changed_entry + .affordance_catalog + .get_mut(&granted) + .unwrap() + .carries_speech = false; + assert_ne!(scope_digest(&changed_entry, scope).unwrap(), base); + + let mut changed_position = kernel.state.clone(); + changed_position.positions.insert( + topology.walker, + Position { + place: topology.road, + }, + ); + assert_ne!(scope_digest(&changed_position, scope).unwrap(), base); + + let mut changed_route = kernel.state.clone(); + changed_route + .edges + .get_mut(&topology.ramp) + .unwrap() + .set_cost(Cost(99)); + assert_ne!(scope_digest(&changed_route, scope).unwrap(), base); + + // The span joins road and gate, so it is incident to neither the walker's + // place nor its scope; an unrelated subject's decision is invisible too. + let mut unrelated_route = kernel.state.clone(); + unrelated_route + .edges + .get_mut(&topology.span) + .unwrap() + .set_cost(Cost(99)); + assert_eq!(scope_digest(&unrelated_route, scope).unwrap(), base); + + let active = kernel.snapshot().unwrap(); + let persona = opportunity(&active, ControllerMode::NarrativePersona); + let persona_caller = CallerId::Controller(persona.controller_id); + kernel + .submit( + command( + &active, + CommandId::new(), + persona_caller.clone(), + CommandBody::ExerciseDecision { + invocation: speak(&persona, "Unrelated."), + opportunity: persona, + }, + ), + &AuthenticatedCaller::fixture(persona_caller), + ) + .unwrap(); + assert_eq!(scope_digest(&kernel.state, scope).unwrap(), base); + } + + #[test] + fn draft_activation_human_and_autonomous_actions_share_one_reducer() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), " Delvehold "), + &auth_principal(owner()), + ) + .unwrap(); + let genesis = kernel.snapshot().unwrap(); + assert_eq!(genesis.title, "Delvehold"); + assert_eq!(genesis.phase, WorldPhase::Draft); + assert!(genesis.opportunities.is_empty()); + + let active = activate(&mut kernel); + assert_eq!(active.phase, WorldPhase::Active); + assert_eq!(active.opportunities.len(), 3); + + let human_opportunity = opportunity(&active, ControllerMode::Human); + kernel + .submit( + command( + &active, + CommandId::new(), + CallerId::Principal(human_principal()), + CommandBody::ExerciseDecision { + invocation: speak(&human_opportunity, "I open the door."), + opportunity: human_opportunity, + }, + ), + &auth_principal(human_principal()), + ) + .unwrap(); + let after_human = kernel.snapshot().unwrap(); + assert_eq!(kernel.state.events.len(), 1); + assert_eq!( + spoken(&kernel.state, &kernel.state.events[0]), + Some("I open the door.") + ); + + let persona_opportunity = opportunity(&after_human, ControllerMode::NarrativePersona); + let persona_caller = CallerId::Controller(persona_opportunity.controller_id); + kernel + .submit( + command( + &after_human, + CommandId::new(), + persona_caller.clone(), + CommandBody::ExerciseDecision { + invocation: speak(&persona_opportunity, "Then mind the hinge."), + opportunity: persona_opportunity, + }, + ), + &AuthenticatedCaller::fixture(persona_caller), + ) + .unwrap(); + let after_persona = kernel.snapshot().unwrap(); + assert_eq!(kernel.state.events.len(), 2); + assert!( + after_persona + .opportunities + .iter() + .all(|value| value.revision == after_persona.revision) + ); + } + + #[test] + fn lifecycle_and_controller_authority_fail_closed_without_commits() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "Held"), + &auth_principal(owner()), + ) + .unwrap(); + let genesis = kernel.snapshot().unwrap(); + assert!(matches!( + kernel.submit( + command( + &genesis, + CommandId::new(), + CallerId::Principal(owner()), + CommandBody::ActivateWorld, + ), + &auth_principal(owner()) + ), + Err(KernelError::MissingApprovals(_)) + )); + assert_eq!(kernel.journal.commit_count(), 1); + + submit_owner(&mut kernel, &genesis, CommandBody::ApproveDraft); + let owner_approved = kernel.snapshot().unwrap(); + assert!(matches!( + kernel.submit( + command( + &owner_approved, + CommandId::new(), + CallerId::Principal(human_principal()), + CommandBody::ActivateWorld, + ), + &auth_principal(human_principal()) + ), + Err(KernelError::Unauthorized) + )); + assert!(matches!( + kernel.submit( + command( + &owner_approved, + CommandId::new(), + CallerId::Principal(owner()), + CommandBody::ApproveDraft, + ), + &auth_principal(owner()) + ), + Err(KernelError::DraftAlreadyApproved) + )); + assert_eq!(kernel.journal.commit_count(), 2); + + kernel + .submit( + command( + &owner_approved, + CommandId::new(), + CallerId::Principal(human_principal()), + CommandBody::ApproveDraft, + ), + &auth_principal(human_principal()), + ) + .unwrap(); + let approved = kernel.snapshot().unwrap(); + submit_owner(&mut kernel, &approved, CommandBody::ActivateWorld); + let active = kernel.snapshot().unwrap(); + let persona = opportunity(&active, ControllerMode::NarrativePersona); + let commits_before_forgery = kernel.journal.commit_count(); + assert!(matches!( + kernel.submit( + command( + &active, + CommandId::new(), + CallerId::Principal(human_principal()), + CommandBody::ExerciseDecision { + invocation: speak(&persona, "Puppet"), + opportunity: persona, + }, + ), + &auth_principal(human_principal()) + ), + Err(KernelError::ControllerMismatch) + )); + assert_eq!(kernel.journal.commit_count(), commits_before_forgery); + assert_eq!(kernel.snapshot().unwrap(), active); + } + + #[test] + fn a_tampered_or_unknown_opportunity_never_commits() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "Exact"), + &auth_principal(owner()), + ) + .unwrap(); + let active = activate(&mut kernel); + let original = opportunity(&active, ControllerMode::Human); + // An entry only the operational subject is granted: the human's scope + // does not hold it, which is what denial means now that an affordance id + // names a catalog entry rather than one subject's copy of one. + let denied_invocation = DecisionInvocation { + affordance: affordance_named(&active, "convene"), + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Statement::new("No grant").unwrap()), + display: None, + }; + assert!(matches!( + kernel.submit( + command( + &active, + CommandId::new(), + CallerId::Principal(human_principal()), + CommandBody::ExerciseDecision { + invocation: denied_invocation, + opportunity: original.clone(), + }, + ), + &auth_principal(human_principal()) + ), + Err(KernelError::AffordanceDenied) + )); + // A claimed affordance the world did not grant carries no authority: the + // kernel exercises the opportunity it derives, never the one submitted. + let forged_affordance = AffordanceId::issue(); + let mut tampered = original.clone(); + tampered.affordance_ids.push(forged_affordance); + assert!(matches!( + kernel.submit( + command( + &active, + CommandId::new(), + CallerId::Principal(human_principal()), + CommandBody::ExerciseDecision { + invocation: DecisionInvocation { + affordance: forged_affordance, + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Statement::new("Forged").unwrap()), + display: None, + }, + opportunity: tampered, + }, + ), + &auth_principal(human_principal()) + ), + Err(KernelError::AffordanceDenied) + )); + assert_eq!(kernel.snapshot().unwrap(), active); + + let mut forged_scope = original.clone(); + forged_scope.scope_digest = ScopeDigest::fixture("sha256:not-this-scope"); + assert!(matches!( + kernel.submit( + command( + &active, + CommandId::new(), + CallerId::Principal(human_principal()), + CommandBody::ExerciseDecision { + invocation: speak(&original, "No"), + opportunity: forged_scope, + }, + ), + &auth_principal(human_principal()) + ), + Err(KernelError::ScopeChanged { .. }) + )); + assert_eq!(kernel.snapshot().unwrap(), active); + + let unknown_scope = DecisionOpportunity { + scope: DecisionScope { + subject_id: SubjectId::issue(), + }, + ..original.clone() + }; + assert!(matches!( + kernel.submit( + command( + &active, + CommandId::new(), + CallerId::Principal(human_principal()), + CommandBody::ExerciseDecision { + invocation: speak(&original, "No"), + opportunity: unknown_scope, + }, + ), + &auth_principal(human_principal()) + ), + Err(KernelError::OpportunityMismatch) + )); + assert_eq!(kernel.snapshot().unwrap(), active); + } + + #[test] + fn create_submit_restart_and_replay_are_exact() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("world.cc"); + let creation = creation(CommandId::new(), "First"); + let (mut kernel, creation_receipt) = + WorldKernel::create(&path, creation.clone(), &auth_principal(owner())).unwrap(); + let active = activate(&mut kernel); + let decision = opportunity(&active, ControllerMode::OperationalAgent); + let caller = CallerId::Controller(decision.controller_id); + let command = command( + &active, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + invocation: speak(&decision, "The vote carries."), + opportunity: decision, + }, + ); + let applied = kernel + .submit( + command.clone(), + &AuthenticatedCaller::fixture(caller.clone()), + ) + .unwrap(); + let SubmitReceipt::Applied(receipt) = applied else { + panic!("expected applied receipt") + }; + let accepted = kernel.snapshot().unwrap(); + drop(kernel); + + let (mut reopened, retried_creation_receipt) = + WorldKernel::create(&path, creation, &auth_principal(owner())).unwrap(); + assert_eq!(retried_creation_receipt, creation_receipt); + assert_eq!(reopened.snapshot().unwrap(), accepted); + assert_eq!( + reopened + .submit(command, &AuthenticatedCaller::fixture(caller)) + .unwrap(), + SubmitReceipt::AlreadyApplied(receipt) + ); + drop(reopened); + let reopened = WorldKernel::open(&path, accepted.world_id).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), accepted); + } + + #[test] + fn controller_receipt_is_bound_to_the_exact_opportunity_and_invocation() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "Receipt Scope"), + &auth_principal(owner()), + ) + .unwrap(); + let active = activate(&mut kernel); + let decision = opportunity(&active, ControllerMode::OperationalAgent); + let other = opportunity(&active, ControllerMode::NarrativePersona); + let command_id = CommandId::new(); + let caller = CallerId::Controller(decision.controller_id); + let invocation = speak(&decision, "The record is exact."); + kernel + .submit( + command( + &active, + command_id, + caller.clone(), + CommandBody::ExerciseDecision { + invocation: invocation.clone(), + opportunity: decision.clone(), + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .unwrap(); + + let receipt = kernel + .controller_receipt(command_id, &decision, &invocation) + .unwrap() + .expect("committed controller command has a receipt"); + assert_eq!(receipt.command_id, command_id); + assert!( + kernel + .controller_receipt(CommandId::new(), &decision, &invocation) + .unwrap() + .is_none() + ); + assert!(matches!( + kernel.controller_receipt(command_id, &other, &invocation), + Err(KernelError::CommandIdConflict) + )); + let altered_invocation = speak(&decision, "A different proposal."); + assert!(matches!( + kernel.controller_receipt(command_id, &decision, &altered_invocation), + Err(KernelError::CommandIdConflict) + )); + } + + #[test] + fn controller_decline_consumes_only_its_exact_opportunity() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "Decline Scope"), + &auth_principal(owner()), + ) + .unwrap(); + let active = activate(&mut kernel); + let decision = opportunity(&active, ControllerMode::OperationalAgent); + let other = opportunity(&active, ControllerMode::NarrativePersona); + let caller = CallerId::Controller(decision.controller_id); + + assert!(matches!( + kernel.submit( + command( + &active, + CommandId::new(), + CallerId::Controller(other.controller_id), + CommandBody::DeclineDecision { + opportunity: decision.clone(), + }, + ), + &AuthenticatedCaller::fixture(CallerId::Controller(other.controller_id)), + ), + Err(KernelError::ControllerMismatch) + )); + assert_eq!(kernel.snapshot().unwrap(), active); + + let command_id = CommandId::new(); + let decline = command( + &active, + command_id, + caller.clone(), + CommandBody::DeclineDecision { + opportunity: decision.clone(), + }, + ); + let SubmitReceipt::Applied(receipt) = kernel + .submit( + decline.clone(), + &AuthenticatedCaller::fixture(caller.clone()), + ) + .unwrap() + else { + panic!("exact decline was not applied") + }; + let after = kernel.snapshot().unwrap(); + assert_eq!(after.revision, active.revision + 1); + assert!(kernel.state.events.is_empty()); + let refreshed = opportunity(&after, ControllerMode::OperationalAgent); + assert_ne!(refreshed, decision); + assert_eq!( + kernel + .controller_decline_receipt(command_id, &decision) + .unwrap(), + Some(receipt.clone()) + ); + assert!(matches!( + kernel.controller_decline_receipt(command_id, &other), + Err(KernelError::CommandIdConflict) + )); + assert!(matches!( + kernel.controller_receipt( + command_id, + &decision, + &speak(&decision, "A decline is not speech."), + ), + Err(KernelError::CommandIdConflict) + )); + assert_eq!( + kernel + .submit(decline, &AuthenticatedCaller::fixture(caller.clone())) + .unwrap(), + SubmitReceipt::AlreadyApplied(receipt.clone()) + ); + assert_eq!(kernel.snapshot().unwrap(), after); + drop(kernel); + let reopened = WorldKernel::open(&path, after.world_id).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), after); + assert_eq!( + reopened + .controller_decline_receipt( + command_id, + &opportunity(&active, ControllerMode::OperationalAgent), + ) + .unwrap(), + Some(receipt) + ); + } + + #[test] + fn duplicate_and_stale_commands_do_not_commit() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "Still"), + &auth_principal(owner()), + ) + .unwrap(); + let genesis = kernel.snapshot().unwrap(); + assert!(matches!( + submit_owner(&mut kernel, &genesis, CommandBody::ApproveDraft), + SubmitReceipt::Applied(_) + )); + let after = kernel.snapshot().unwrap(); + assert!(matches!( + kernel.submit( + command( + &after, + CommandId::new(), + CallerId::Principal(owner()), + CommandBody::ApproveDraft, + ), + &auth_principal(owner()) + ), + Err(KernelError::DraftAlreadyApproved) + )); + let stale = command( + &genesis, + CommandId::new(), + CallerId::Principal(owner()), + CommandBody::ApproveDraft, + ); + assert!(matches!( + kernel.submit(stale, &auth_principal(owner())), + Err(KernelError::RevisionMismatch { .. }) + )); + assert_eq!(kernel.snapshot().unwrap(), after); + assert_eq!(kernel.journal.commit_count(), 2); + } + + #[test] + fn durable_idempotency_precedes_revision_and_detects_conflicts() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "A"), + &auth_principal(owner()), + ) + .unwrap(); + let genesis = kernel.snapshot().unwrap(); + let id = CommandId::new(); + let first = command( + &genesis, + id, + CallerId::Principal(owner()), + CommandBody::ApproveDraft, + ); + let first_receipt = kernel + .submit(first.clone(), &auth_principal(owner())) + .unwrap(); + let second_snapshot = kernel.snapshot().unwrap(); + kernel + .submit( + command( + &second_snapshot, + CommandId::new(), + CallerId::Principal(human_principal()), + CommandBody::ApproveDraft, + ), + &auth_principal(human_principal()), + ) + .unwrap(); + let after_second = kernel.snapshot().unwrap(); + assert_eq!( + kernel.submit(first, &auth_principal(owner())).unwrap(), + match first_receipt { + SubmitReceipt::Applied(value) => SubmitReceipt::AlreadyApplied(value), + _ => unreachable!(), + } + ); + let conflict = command( + &genesis, + id, + CallerId::Principal(owner()), + CommandBody::ActivateWorld, + ); + assert!(matches!( + kernel.submit(conflict, &auth_principal(owner())), + Err(KernelError::CommandIdConflict) + )); + assert_eq!(kernel.snapshot().unwrap(), after_second); + } + + #[test] + fn creation_retry_is_bound_to_the_exact_raw_command() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("world.cc"); + let id = CommandId::new(); + let raw = creation(id, " Canonical Result "); + let (kernel, first) = + WorldKernel::create(&path, raw.clone(), &auth_principal(owner())).unwrap(); + assert_eq!(kernel.snapshot().unwrap().title, "Canonical Result"); + drop(kernel); + + let (kernel, retry) = + WorldKernel::create(&path, raw.clone(), &auth_principal(owner())).unwrap(); + assert_eq!(retry, first); + drop(kernel); + + let mut merely_equivalent = raw; + merely_equivalent.title = "Canonical Result".into(); + assert!(matches!( + WorldKernel::create(&path, merely_equivalent, &auth_principal(owner())), + Err(KernelError::CreationConflict) + )); + } + + #[test] + fn invalid_seed_never_allocates_a_world() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("world.cc"); + let mut invalid = creation(CommandId::new(), "Nope"); + invalid.patch.declarations[3] = invalid.patch.declarations[2].clone(); + let Err(KernelError::PatchRejected(rejected)) = + WorldKernel::create(&path, invalid, &auth_principal(owner())) + else { + panic!("expected a rejected creation patch"); + }; + assert_eq!( + rejected, + vec![Mismatch::DuplicateHandle { + handle: DraftHandle::new("human") + }] + ); + assert!( + WorldKernel::create( + &path, + creation(CommandId::new(), "Valid"), + &auth_principal(owner()) + ) + .is_ok() + ); + } + + #[test] + fn a_second_live_owner_is_refused() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("world.cc"); + let creation = creation(CommandId::new(), "Held"); + let (kernel, _) = + WorldKernel::create(&path, creation.clone(), &auth_principal(owner())).unwrap(); + let world_id = kernel.snapshot().unwrap().world_id; + assert!(matches!( + WorldKernel::open(&path, world_id), + Err(KernelError::Store(_)) + )); + assert!(matches!( + WorldKernel::create(&path, creation.clone(), &auth_principal(owner())), + Err(KernelError::Store(_)) + )); + drop(kernel); + let kernel = WorldKernel::open(&path, world_id).unwrap(); + drop(kernel); + assert!(matches!( + WorldKernel::open(&path, WorldId::issue()), + Err(KernelError::OpenedWorldMismatch) + )); + } + + #[test] + fn lost_post_commit_ack_poisons_until_reopen_and_exact_retry() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "Certain"), + &auth_principal(owner()), + ) + .unwrap(); + let genesis = kernel.snapshot().unwrap(); + let uncertain = CommandId::new(); + let attempted = command( + &genesis, + uncertain, + CallerId::Principal(owner()), + CommandBody::ApproveDraft, + ); + kernel.journal.fail_after_durable_commit_for_test(); + assert!(matches!( + kernel.submit(attempted.clone(), &auth_principal(owner())), + Err(KernelError::RecoveryRequired { command_id }) if command_id == uncertain + )); + assert!(matches!( + kernel.snapshot(), + Err(KernelError::RecoveryRequired { command_id }) if command_id == uncertain + )); + drop(kernel); + + let mut reopened = WorldKernel::open(&path, genesis.world_id).unwrap(); + let durable = reopened.snapshot().unwrap(); + assert_eq!(durable.revision, 1); + assert_eq!(durable.draft_approvals, BTreeSet::from([owner()])); + assert!(matches!( + reopened + .submit(attempted, &auth_principal(owner())) + .unwrap(), + SubmitReceipt::AlreadyApplied(_) + )); + } + + #[test] + fn lost_genesis_ack_reopens_as_the_same_world_and_exact_receipt() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("world.cc"); + let command_id = CommandId::new(); + let input = creation(command_id, "Durable Genesis"); + let authenticated = auth_principal(owner()); + let mut empty = match journal::WorldJournal::open_owner(&path).unwrap() { + journal::JournalOpen::Empty(empty) => empty, + journal::JournalOpen::Live { .. } => panic!("fixture store must be empty"), + }; + empty.fail_after_durable_initialize_for_test(); + let prepared = prepare_creation(input.clone(), &authenticated).unwrap(); + assert!(matches!( + WorldKernel::initialize(empty, prepared), + Err(KernelError::RecoveryRequired { command_id: uncertain }) + if uncertain == command_id + )); + + let (reopened, receipt) = WorldKernel::create(&path, input, &authenticated).unwrap(); + let snapshot = reopened.snapshot().unwrap(); + assert_eq!(receipt.command_id, command_id); + assert_eq!(receipt.world_id, snapshot.world_id); + assert_eq!(snapshot.revision, 0); + assert_eq!(snapshot.title, "Durable Genesis"); + } + + #[test] + fn replacing_the_store_path_revokes_the_live_owner() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("world.cc"); + let displaced = dir.path().join("displaced.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "Pinned"), + &auth_principal(owner()), + ) + .unwrap(); + let snapshot = kernel.snapshot().unwrap(); + std::fs::rename(&path, &displaced).unwrap(); + std::fs::File::create(&path).unwrap(); + assert!(matches!(kernel.snapshot(), Err(KernelError::OwnershipLost))); + assert!(matches!( + kernel.submit( + command( + &snapshot, + CommandId::new(), + CallerId::Principal(owner()), + CommandBody::ApproveDraft, + ), + &auth_principal(owner()) + ), + Err(KernelError::OwnershipLost) + )); + std::fs::remove_file(&path).unwrap(); + std::fs::rename(&displaced, &path).unwrap(); + assert!(matches!(kernel.snapshot(), Err(KernelError::OwnershipLost))); + drop(kernel); + let reopened = WorldKernel::open(&path, snapshot.world_id).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), snapshot); + } + + #[test] + fn sealed_authentication_cannot_be_replaced_by_a_command_claim() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "Owned"), + &auth_principal(owner()), + ) + .unwrap(); + let snapshot = kernel.snapshot().unwrap(); + let forged = command( + &snapshot, + CommandId::new(), + CallerId::Principal(human_principal()), + CommandBody::ApproveDraft, + ); + assert!(matches!( + kernel.submit(forged, &auth_principal(owner())), + Err(KernelError::AuthenticationMismatch) + )); + assert_eq!(kernel.snapshot().unwrap(), snapshot); + } + + /// Soul falsification: the preimage must exclude the revision, the phase, + /// and every component outside the scope. Each step below is a real commit + /// that moves the world, not a hand-edited state. + #[test] + fn soul_scope_digest_excludes_revision_phase_and_everything_outside_the_scope() { + let dir = tempfile::tempdir().unwrap(); + let (mut kernel, _) = WorldKernel::create( + dir.path().join("world.cc"), + creation(CommandId::new(), "Preimage"), + &auth_principal(owner()), + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + let scope = DecisionScope { + subject_id: topology.walker, + }; + let base = scope_digest(&kernel.state, scope).unwrap(); + let start_revision = kernel.state.revision; + + // A new place elsewhere, a route that touches neither the walker's + // place nor it, and a second placed subject: all outside the scope. + let speak = speak_entry(&kernel); + let before = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &before, + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("annex"), + label: "The Annex".into(), + kind: EntityKind::Place, + container: None, + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("annexway"), + label: "The Annex Way".into(), + from: Ref::Existing(topology.road), + to: Ref::Draft(DraftHandle::new("annex")), + access: AccessKind::Public, + cost: Cost(3), + }), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("runner"), + label: "The Runner".into(), + kind: SubjectKind::Person, + controller: NewController::OperationalAgent, + affordances: BTreeSet::from([speak.clone()]), + position: Some(Ref::Existing(topology.road)), + import_key: None, + }), + ], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ); + assert_ne!(kernel.state.revision, start_revision); + assert_eq!(scope_digest(&kernel.state, scope).unwrap(), base); + + // Activation changes the phase, the approvals, and the revision. + let active = activate(&mut kernel); + assert_eq!(active.phase, WorldPhase::Active); + assert_eq!(scope_digest(&kernel.state, scope).unwrap(), base); + + // Another subject's Position moving is not this scope's business. + let annexway = *kernel + .state + .edges + .iter() + .find(|(_, record)| record.label() == "The Annex Way") + .expect("the declared route") + .0; + let runner = *kernel + .state + .subjects + .iter() + .find(|(_, subject)| subject.label == "The Runner") + .expect("the declared subject") + .0; + let active = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &active, + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Relocate { + subject: Ref::Existing(runner), + via: Ref::Existing(annexway), + }], + evidence: Vec::new(), + }, + }, + ); + assert_eq!( + kernel.state.positions.get(&runner), + Some(&Position { + place: kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == "The Annex") + .map(|(id, _)| *id) + .unwrap() + }) + ); + assert_eq!(scope_digest(&kernel.state, scope).unwrap(), base); + + // A route incident to the walker's own place is inside the scope. + let moved = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &moved, + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::CloseRoute { + route: Ref::Existing(topology.ramp), + }], + evidence: Vec::new(), + }, + }, + ); + assert_ne!(scope_digest(&kernel.state, scope).unwrap(), base); + } + + /// Soul falsification: a claimed opportunity whose `affordance_ids` name + /// grants this scope does not hold cannot widen authority. The kernel reads + /// the derived list, so the forged one is ignored and the invocation is + /// denied on the real grants. + #[test] + fn soul_a_forged_affordance_list_cannot_widen_authority() { + let dir = tempfile::tempdir().unwrap(); + let (mut kernel, _) = WorldKernel::create( + dir.path().join("world.cc"), + creation(CommandId::new(), "Affordances"), + &auth_principal(owner()), + ) + .unwrap(); + let active = activate(&mut kernel); + let persona = opportunity(&active, ControllerMode::NarrativePersona); + let operator = opportunity(&active, ControllerMode::OperationalAgent); + + // The persona claims the operator's entry and lists it as its own. + let convened = affordance_named(&active, "convene"); + assert!(operator.affordance_ids.contains(&convened)); + assert!(!persona.affordance_ids.contains(&convened)); + let mut forged = persona.clone(); + forged.affordance_ids = vec![convened, persona.affordance_ids[0]]; + let caller = CallerId::Controller(persona.controller_id); + let error = kernel + .submit( + command( + &active, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + opportunity: forged, + invocation: DecisionInvocation { + affordance: convened, + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Statement::new("Not my grant.").unwrap()), + display: None, + }, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .unwrap_err(); + assert!(matches!(error, KernelError::AffordanceDenied)); + assert_eq!(kernel.snapshot().unwrap(), active); + } + + /// Soul: an `AffordanceId` now names a catalog entry, not a subject's copy + /// of one — the three genesis subjects share Speak's single id. So the id + /// cannot be what gates: grant membership for the invoking scope is. The + /// same `convene` id commits for the scope that holds it and is denied for + /// one that does not. + #[test] + fn soul_a_shared_catalog_id_is_gated_by_the_scope_grant() { + let dir = tempfile::tempdir().unwrap(); + let (mut kernel, _) = WorldKernel::create( + dir.path().join("world.cc"), + creation(CommandId::new(), "SharedCatalogIds"), + &auth_principal(owner()), + ) + .unwrap(); + let active = activate(&mut kernel); + let speak = affordance_named(&active, "speak"); + let convened = affordance_named(&active, "convene"); + + // One entry, one id, every genesis subject a grantee. + assert_eq!(active.subjects.len(), 3); + assert!( + active + .subjects + .iter() + .all(|subject| subject.affordances.contains(&speak)) + ); + assert!( + active + .opportunities + .iter() + .all(|opportunity| opportunity.affordance_ids.contains(&speak)) + ); + let holders: Vec = active + .subjects + .iter() + .filter(|subject| subject.affordances.contains(&convened)) + .map(|subject| subject.id) + .collect(); + assert_eq!(holders.len(), 1); + + let invoke = |kernel: &mut WorldKernel, snapshot: &WorldSnapshot, subject: SubjectId| { + let opportunity = opportunity_for(snapshot, subject); + let caller = CallerId::Controller(opportunity.controller_id); + kernel.submit( + command( + snapshot, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + opportunity, + invocation: DecisionInvocation { + affordance: convened, + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Statement::new("The council convenes.").unwrap()), + display: None, + }, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + }; + + // The grantee's scope commits with that id. + assert!(matches!( + invoke(&mut kernel, &active, holders[0]).unwrap(), + SubmitReceipt::Applied(_) + )); + + // A scope that does not hold the entry is denied the very same id, and + // nothing commits. + let after = kernel.snapshot().unwrap(); + // A controller-driven scope, so the denial is the grant check rather + // than the human lane's caller check reached first. + let stranger = after + .subjects + .iter() + .find(|subject| { + !subject.affordances.contains(&convened) && subject.human_controller.is_none() + }) + .expect("a controller-driven subject without the grant") + .id; + assert!(matches!( + invoke(&mut kernel, &after, stranger).unwrap_err(), + KernelError::AffordanceDenied + )); + assert_eq!(kernel.snapshot().unwrap(), after); + } + + #[test] + fn a_stale_grant_rejects_but_a_distant_route_reaches_admission_instead() { + let dir = tempfile::tempdir().unwrap(); + let (mut kernel, _) = WorldKernel::create( + dir.path().join("world.cc"), + creation(CommandId::new(), "BindingAndAdmission"), + &auth_principal(owner()), + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + let active = activate(&mut kernel); + let bound = opportunity_for(&active, topology.walker); + let speak = affordance_named(&active, "speak"); + + // Binding is scope-digest equality, and the digest reads the granted + // entries' definitions: altering one moves the digest, so a proposal + // bound before that change no longer binds. + let mut altered = kernel.state.clone(); + altered + .affordance_catalog + .get_mut(&speak) + .expect("the Speak entry") + .carries_speech = false; + assert_ne!( + scope_digest(&altered, bound.scope).unwrap(), + scope_digest(&kernel.state, bound.scope).unwrap() + ); + + // A route the actor does not stand beside is outside the digest, so + // closing it leaves the binding intact. That is deliberate: admission + // re-reads the live graph at commit, so nothing commits on stale + // topology and a proposal is not invalidated by distant traffic. + let before_digest = scope_digest(&kernel.state, bound.scope).unwrap(); + let before = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &before, + operations(vec![ComponentOp::CloseRoute { + route: Ref::Existing(topology.span), + }]), + ); + assert_eq!( + scope_digest(&kernel.state, bound.scope).unwrap(), + before_digest, + "a route outside the actor's incident set does not rebind the proposal" + ); + + let snapshot = kernel.snapshot().unwrap(); + let receipt = kernel + .submit( + command( + &snapshot, + CommandId::new(), + CallerId::Controller(bound.controller_id), + CommandBody::ExerciseDecision { + opportunity: bound.clone(), + invocation: DecisionInvocation { + affordance: speak, + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Statement::new("Still here.").unwrap()), + display: None, + }, + }, + ), + &AuthenticatedCaller::fixture(CallerId::Controller(bound.controller_id)), + ) + .expect("a distant route closing does not rebind this proposal"); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + } + + /// The mvp doc's disjointness requirement: an institution with an + /// operational organ and a person-shaped voice is two subjects joined by an + /// office, not one subject with two controllers. + #[test] + fn an_institution_and_its_voice_are_two_subjects_joined_by_an_office() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = crate::custody_tests::custody_kernel(directory.path(), "Two"); + let (_, civic, active) = civic_world(&mut kernel); + + let treasury = opportunity_for(&active, civic.treasury); + let reeve = opportunity_for(&active, civic.reeve); + assert_ne!(treasury.controller_id, reeve.controller_id); + assert_eq!( + active + .opportunities + .iter() + .filter(|value| value.scope.subject_id == civic.treasury) + .count(), + 1 + ); + assert_eq!( + active + .opportunities + .iter() + .filter(|value| value.scope.subject_id == civic.reeve) + .count(), + 1 + ); + + // Both are authorized over the hall — one directly, one by delegation — + // and neither appears in the other's components. + let over_hall = AuthorityGrant { + kind: authority_kind(LEVY_KIND), + over: AuthorityTarget::PlaceSubtree(civic.hall), + }; + assert!(subject_authority(&kernel.state, civic.treasury).contains(&over_hall)); + assert!(subject_authority(&kernel.state, civic.reeve).contains(&over_hall)); + assert!(kernel.state.authority.get(&civic.reeve).is_none()); + assert!( + scope_components(&kernel.state, civic.treasury) + .delegated + .is_empty() + ); + assert!( + scope_components(&kernel.state, civic.reeve) + .authority + .is_empty() + ); + } + + /// A levy from catalog to conservation: one lowered `Transfer`, the ledger + /// total unchanged, and no other partition touched. + #[test] + fn a_levy_round_trips_from_catalog_to_conservation() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = crate::custody_tests::custody_kernel(directory.path(), "Levy"); + let (_, civic, active) = civic_world(&mut kernel); + let before_total: u64 = kernel + .state + .holdings + .values() + .filter_map(|held| held.get(&civic.grain)) + .map(|quantity| quantity.0) + .sum(); + let positions = kernel.state.positions.clone(); + let edges = kernel.state.edges.clone(); + let entities = kernel.state.entities.clone(); + + let opportunity = opportunity_for(&active, civic.treasury); + let caller = CallerId::Controller(opportunity.controller_id); + let receipt = kernel + .submit( + command( + &active, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + opportunity, + invocation: DecisionInvocation { + affordance: affordance_named(&active, "levy"), + bindings: vec![ + RoleBinding { + role: Role("payer".into()), + target: Target::Subject(civic.farmer), + }, + RoleBinding { + role: Role("resource".into()), + target: Target::Entity(civic.grain), + }, + ], + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::Quantity(Quantity(3)), + }], + speech: None, + display: None, + }, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .unwrap(); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + + let held = |holder: SubjectId| { + kernel + .state + .holdings + .get(&holder) + .and_then(|held| held.get(&civic.grain)) + .map_or(0, |quantity| quantity.0) + }; + assert_eq!(held(civic.farmer), OPENING_BALANCE - 3); + assert_eq!(held(civic.treasury), 3); + let after_total: u64 = kernel + .state + .holdings + .values() + .filter_map(|held| held.get(&civic.grain)) + .map(|quantity| quantity.0) + .sum(); + assert_eq!(before_total, after_total); + assert_eq!( + kernel.state.events.last().unwrap().effects, + vec![ResolvedOp::Transfer { + from: civic.farmer, + to: civic.treasury, + resource: civic.grain, + qty: Quantity(3), + }] + ); + assert_eq!(kernel.state.positions, positions); + assert_eq!(kernel.state.edges, edges); + assert_eq!(kernel.state.entities, entities); + } + + /// Representation is person-and-institution shaped, and that is the check + /// that stops the two-subject shape from collapsing back into one. + #[test] + fn office_admission_is_person_and_institution_shaped() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = crate::custody_tests::custody_kernel(directory.path(), "Offices"); + let (_, civic, _) = civic_world(&mut kernel); + let refuse = |kernel: &mut WorldKernel, ops: Vec| { + let before = kernel.snapshot().unwrap(); + reject_owner(kernel, &before, operations(ops)) + }; + + // An institution cannot occupy its own office. + assert_eq!( + refuse( + &mut kernel, + vec![ComponentOp::InstallIncumbent { + institution: Ref::Existing(civic.treasury), + office: office(BAILIFF_OFFICE), + incumbent: Ref::Existing(civic.treasury), + }] + ), + vec![Mismatch::OfficeHolderNotPerson { operation: 0 }] + ); + // An office cannot be opened on a person. + assert_eq!( + refuse( + &mut kernel, + vec![ComponentOp::OpenOffice { + institution: Ref::Existing(civic.reeve), + office: office(WARDEN_OFFICE), + delegated: BTreeSet::from([authority_kind(LEVY_KIND)]), + }] + ), + vec![Mismatch::OfficeOnNonInstitution { operation: 0 }] + ); + // One person, at most one office per institution. + assert_eq!( + refuse( + &mut kernel, + vec![ComponentOp::InstallIncumbent { + institution: Ref::Existing(civic.treasury), + office: office(BAILIFF_OFFICE), + incumbent: Ref::Existing(civic.reeve), + }] + ), + vec![Mismatch::DuplicateIncumbency { operation: 0 }] + ); + } + + /// Disjointness in both directions: overlap inside one subject's effective + /// authority is refused, overlap between subjects is layered government. + #[test] + fn overlapping_jurisdiction_within_one_subject_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = crate::custody_tests::custody_kernel(directory.path(), "Overlap"); + let (_, civic, _) = civic_world(&mut kernel); + let refuse = |kernel: &mut WorldKernel, ops: Vec| { + let before = kernel.snapshot().unwrap(); + reject_owner(kernel, &before, operations(ops)) + }; + let admit = |kernel: &mut WorldKernel, ops: Vec| { + let before = kernel.snapshot().unwrap(); + submit_owner(kernel, &before, operations(ops)) + }; + + // A direct grant under what the reeve's office already lends. + assert_eq!( + refuse( + &mut kernel, + vec![grant_to(civic.reeve, LEVY_KIND, over_place(civic.chamber))] + ), + vec![Mismatch::OverlappingJurisdiction { operation: 0 }] + ); + // Two direct grants of one kind, nested, in one patch. + assert_eq!( + refuse( + &mut kernel, + vec![ + grant_to(civic.farmer, LEVY_KIND, over_place(civic.hall)), + grant_to(civic.farmer, LEVY_KIND, over_place(civic.chamber)), + ] + ), + vec![Mismatch::OverlappingJurisdiction { operation: 1 }] + ); + // An incumbency that would lend the farmer ground it already holds. + admit( + &mut kernel, + vec![grant_to(civic.farmer, LEVY_KIND, over_place(civic.chamber))], + ); + assert_eq!( + refuse( + &mut kernel, + vec![ComponentOp::InstallIncumbent { + institution: Ref::Existing(civic.treasury), + office: office(WARDEN_OFFICE), + incumbent: Ref::Existing(civic.farmer), + }] + ), + vec![Mismatch::OverlappingJurisdiction { operation: 0 }] + ); + + // A different kind over the same ground commits, and so does the same + // kind held by a different subject: two holders authorized over one + // target is not a contradiction, because nothing arbitrates. + assert!(matches!( + admit( + &mut kernel, + vec![ + grant_to(civic.reeve, JUDGE_KIND, over_place(civic.chamber)), + grant_to(civic.outsider, LEVY_KIND, over_place(civic.chamber)), + ] + ), + SubmitReceipt::Applied(_) + )); + } + + /// Contract 6 on the civic surface: one patch, the complete sorted set, no + /// allocation, and repairing exactly those failures commits. + #[test] + fn civic_operations_are_rejected_with_the_complete_set() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = crate::custody_tests::custody_kernel(directory.path(), "CivicSet"); + let (_, civic, _) = civic_world(&mut kernel); + let before = kernel.snapshot().unwrap(); + let broken = vec![ + ComponentOp::OpenOffice { + institution: Ref::Existing(civic.treasury), + office: office("steward"), + delegated: BTreeSet::new(), + }, + ComponentOp::InstallIncumbent { + institution: Ref::Existing(civic.treasury), + office: office("provost"), + incumbent: Ref::Existing(civic.farmer), + }, + ComponentOp::CloseForum { + grievance: grievance("eviction"), + }, + ComponentOp::OpenOffice { + institution: Ref::Existing(civic.treasury), + office: office("Chief Steward"), + delegated: BTreeSet::from([authority_kind(JUDGE_KIND)]), + }, + ComponentOp::InstallIncumbent { + institution: Ref::Existing(civic.treasury), + office: office(BAILIFF_OFFICE), + incumbent: Ref::Existing(civic.treasury), + }, + grant_to(civic.reeve, LEVY_KIND, over_place(civic.chamber)), + ]; + let mut expected = vec![ + Mismatch::EmptyDelegation { operation: 0 }, + Mismatch::UnknownOffice { operation: 1 }, + Mismatch::UnknownForum { operation: 2 }, + Mismatch::InvalidCivicName { + site: patch::Site::Operation(3), + }, + Mismatch::OfficeHolderNotPerson { operation: 4 }, + Mismatch::OverlappingJurisdiction { operation: 5 }, + ]; + expected.sort(); + assert_eq!( + reject_owner(&mut kernel, &before, operations(broken)), + expected + ); + assert_eq!(kernel.snapshot().unwrap(), before); + + let repaired = vec![ + ComponentOp::OpenOffice { + institution: Ref::Existing(civic.treasury), + office: office("steward"), + delegated: BTreeSet::from([authority_kind(JUDGE_KIND)]), + }, + ComponentOp::InstallIncumbent { + institution: Ref::Existing(civic.treasury), + office: office("steward"), + incumbent: Ref::Existing(civic.farmer), + }, + ComponentOp::OpenForum { + grievance: grievance("eviction"), + forum: Ref::Existing(civic.treasury), + standing: over_place(civic.hall), + }, + ]; + assert!(matches!( + submit_owner(&mut kernel, &before, operations(repaired)), + SubmitReceipt::Applied(_) + )); + } + + /// A civic operation that changes nothing is not a canonical change. + #[test] + fn an_idempotent_civic_operation_is_no_change() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = + crate::custody_tests::custody_kernel(directory.path(), "Idempotent"); + let (_, civic, _) = civic_world(&mut kernel); + for operation in [ + grant_to(civic.treasury, LEVY_KIND, over_place(civic.hall)), + ComponentOp::RevokeAuthority { + holder: Ref::Existing(civic.treasury), + grant: grant_of(JUDGE_KIND, over_place(civic.hall)), + }, + ComponentOp::VacateOffice { + institution: Ref::Existing(civic.treasury), + office: office(BAILIFF_OFFICE), + }, + ComponentOp::OpenForum { + grievance: grievance(SEIZURE_GRIEVANCE), + forum: Ref::Existing(civic.treasury), + standing: over_place(civic.chamber), + }, + ComponentOp::OpenOffice { + institution: Ref::Existing(civic.treasury), + office: office(WARDEN_OFFICE), + delegated: BTreeSet::from([authority_kind(LEVY_KIND)]), + }, + ] { + let before = kernel.snapshot().unwrap(); + assert_eq!( + reject_owner(&mut kernel, &before, operations(vec![operation])), + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + } + } + + /// The digest reads what the actor is authorized over and nothing about the + /// world the actor reaches. + #[test] + fn scope_digest_reads_authority_and_delegation_but_not_occupancy() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = crate::custody_tests::custody_kernel(directory.path(), "Digest"); + let (topology, civic, _) = civic_world(&mut kernel); + let scope = |subject_id| DecisionScope { subject_id }; + let digest_of = |kernel: &WorldKernel, subject_id| { + scope_digest(&kernel.state, scope(subject_id)).unwrap() + }; + let admit = |kernel: &mut WorldKernel, ops: Vec| { + let before = kernel.snapshot().unwrap(); + submit_owner(kernel, &before, operations(ops)); + }; + + // Moving an unrelated subject into and out of the jurisdiction, and + // opening a forum, leave every digest alone. + let reeve_before = digest_of(&kernel, civic.reeve); + let treasury_before = digest_of(&kernel, civic.treasury); + admit( + &mut kernel, + vec![ + ComponentOp::Relocate { + subject: Ref::Existing(topology.walker), + via: Ref::Existing(topology.ramp), + }, + ComponentOp::OpenForum { + grievance: grievance("eviction"), + forum: Ref::Existing(civic.treasury), + standing: over_place(civic.hall), + }, + ], + ); + assert_eq!(digest_of(&kernel, civic.reeve), reeve_before); + assert_eq!(digest_of(&kernel, civic.treasury), treasury_before); + + // Installing an office the subject does not hold leaves it alone too. + admit( + &mut kernel, + vec![ComponentOp::InstallIncumbent { + institution: Ref::Existing(civic.treasury), + office: office(BAILIFF_OFFICE), + incumbent: Ref::Existing(civic.farmer), + }], + ); + assert_eq!(digest_of(&kernel, civic.reeve), reeve_before); + assert_eq!(digest_of(&kernel, civic.treasury), treasury_before); + + // Revoking the institution's grant for a lent kind moves the + // incumbent's digest, because the office copies it in. + admit( + &mut kernel, + vec![ComponentOp::RevokeAuthority { + holder: Ref::Existing(civic.treasury), + grant: grant_of(LEVY_KIND, over_place(civic.hall)), + }], + ); + assert_ne!(digest_of(&kernel, civic.reeve), reeve_before); + assert_ne!(digest_of(&kernel, civic.treasury), treasury_before); + + // Granting the actor's own, and narrowing a held office, move it too. + let reeve_before = digest_of(&kernel, civic.reeve); + admit( + &mut kernel, + vec![grant_to(civic.reeve, LEVY_KIND, over_place(civic.chamber))], + ); + assert_ne!(digest_of(&kernel, civic.reeve), reeve_before); + let reeve_before = digest_of(&kernel, civic.reeve); + admit( + &mut kernel, + vec![ComponentOp::OpenOffice { + institution: Ref::Existing(civic.treasury), + office: office(WARDEN_OFFICE), + delegated: BTreeSet::from([authority_kind(COMMAND_KIND)]), + }], + ); + assert_ne!(digest_of(&kernel, civic.reeve), reeve_before); + let reeve_before = digest_of(&kernel, civic.reeve); + admit( + &mut kernel, + vec![ComponentOp::VacateOffice { + institution: Ref::Existing(civic.treasury), + office: office(WARDEN_OFFICE), + }], + ); + assert_ne!(digest_of(&kernel, civic.reeve), reeve_before); + } + + /// The snapshot carries a subject's own civic state and no gazetteer: a + /// forum is visible only to its standing, and no subject sees another's + /// grants. + #[test] + fn a_forum_is_visible_only_to_its_standing() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = crate::custody_tests::custody_kernel(directory.path(), "Redress"); + let (_, civic, active) = civic_world(&mut kernel); + let of = |subject_id: SubjectId| { + active + .subjects + .iter() + .find(|subject| subject.id == subject_id) + .expect("a declared subject") + }; + + // The farmer stands in the chamber, which is the forum's standing. + assert_eq!( + of(civic.farmer).redress, + vec![ForumSnapshot { + grievance: grievance(SEIZURE_GRIEVANCE), + forum: civic.treasury, + }] + ); + assert!(of(civic.outsider).redress.is_empty()); + + // Grants are the subject's own; offices held and offices granted are + // the two ends of one link and never merge. + assert!(of(civic.reeve).components.authority.is_empty()); + assert_eq!(of(civic.reeve).offices_held.len(), 1); + assert!(of(civic.reeve).offices_granted.is_empty()); + assert_eq!(of(civic.treasury).offices_granted.len(), 2); + assert!(of(civic.treasury).offices_held.is_empty()); + assert!(of(civic.farmer).components.authority.is_empty()); + assert_eq!( + of(civic.treasury).components.authority, + BTreeSet::from([ + AuthorityGrant { + kind: authority_kind(LEVY_KIND), + over: AuthorityTarget::PlaceSubtree(civic.hall), + }, + AuthorityGrant { + kind: authority_kind(COMMAND_KIND), + over: AuthorityTarget::PlaceSubtree(civic.hall), + }, + ]) + ); + } + + /// Soul falsification of the candidate authority shadow's reach: a grant + /// minted in the same patch resolves, but a *destination* declared in the + /// same patch does not, because the shadow is projected to canonical + /// referents before the covering predicate runs. A genesis patch therefore + /// cannot declare a restricted room and walk anyone into it in one batch. + #[test] + fn a_same_patch_destination_is_covered_by_no_grant() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = crate::custody_tests::custody_kernel(directory.path(), "DraftDoor"); + let topology = admit_topology(&mut kernel); + let before = kernel.snapshot().unwrap(); + let patch = WorldPatch { + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("keep"), + label: "The Inner Keep".into(), + kind: EntityKind::Place, + container: None, + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("keepgate"), + label: "The Keep Gate".into(), + from: Ref::Existing(topology.yard), + to: Ref::Draft(DraftHandle::new("keep")), + access: AccessKind::Restricted { + requires: authority_kind(ADMIT_KIND), + }, + cost: Cost(2), + }), + ], + operations: vec![ + ComponentOp::GrantAuthority { + holder: Ref::Existing(topology.walker), + grant: AuthorityGrantRef { + kind: authority_kind(ADMIT_KIND), + over: AuthorityTargetRef::PlaceSubtree(Ref::Draft(DraftHandle::new( + "keep", + ))), + }, + }, + ComponentOp::Relocate { + subject: Ref::Existing(topology.walker), + via: Ref::Draft(DraftHandle::new("keepgate")), + }, + ], + evidence: Vec::new(), + }; + assert_eq!( + reject_owner( + &mut kernel, + &before, + CommandBody::AdmitPatch { + answers: None, + patch + } + ), + vec![Mismatch::RouteAccessRestricted { operation: 1 }], + "the key covers the door, but the door's far side is still a draft" + ); + } + + /// PA.f38: a retired institution lends nothing. `Retire` does not vacate + /// the office the reeve holds — the incumbency stays on the ledger — but + /// `delegated_authority` stops reading a dissolved institution's grants, + /// the one site that turns an office into effective authority. + #[test] + fn a_retired_institution_lends_no_authority_to_its_office_holder() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = crate::custody_tests::custody_kernel(directory.path(), "RetiredLends"); + let (_, civic, before) = civic_world(&mut kernel); + let over_hall = AuthorityGrant { + kind: authority_kind(LEVY_KIND), + over: AuthorityTarget::PlaceSubtree(civic.hall), + }; + assert!( + subject_authority(&kernel.state, civic.reeve).contains(&over_hall), + "the reeve holds levy only through the warden office before retirement" + ); + + submit_owner( + &mut kernel, + &before, + operations(vec![ComponentOp::Retire { + subject: Ref::Existing(civic.treasury), + }]), + ); + + let warden = kernel + .state + .selection + .get(&civic.treasury) + .and_then(|offices| offices.get(&office(WARDEN_OFFICE))) + .expect("retire did not vacate the office"); + assert_eq!( + warden.incumbent, + Some(civic.reeve), + "the reeve still holds the office after the institution retires" + ); + assert!( + !subject_authority(&kernel.state, civic.reeve).contains(&over_hall), + "a retired institution still lent authority through its office" + ); + } +} + +#[cfg(test)] +mod custody_tests { + use super::tests::{ + OPENING_BALANCE, TITHE_RECEIPT, activate, admit_custody, admit_topology, auth_principal, + command, creation, custody_world, operations, opportunity_for, owner, reject_owner, + speak_entry, submit_owner, + }; + use super::*; + + pub(crate) fn custody_kernel(path: &Path, title: &str) -> WorldKernel { + WorldKernel::create( + path.join("world.cc"), + creation(CommandId::new(), title), + &auth_principal(owner()), + ) + .expect("a created world") + .0 + } + + fn holding(kernel: &WorldKernel, holder: SubjectId, resource: EntityId) -> u64 { + held(&kernel.state, holder, resource) + } + + /// A forged `PatchAdmitted` never passes the resolver, so `admit_resolved` + /// re-derives every custody precondition from the committed partitions and + /// commits nothing when one fails. + /// + /// Deviation from the spec's wording, decided here: `ResolvedOp::Transfer` + /// carries one `qty`, so "a transfer whose debit and credit differ" is + /// unrepresentable — which is the stronger outcome that shape was chosen + /// for. The reachable forgery is a transfer the holder cannot cover, and + /// the conservation equation itself is falsified directly beside it. + #[test] + fn a_non_conserving_transfer_effect_does_not_apply() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "Forged"); + let (_, custody, _) = custody_world(&mut kernel); + let before = kernel.state.holdings.clone(); + + let mut candidate = kernel.state.clone(); + let forged = WorldEffect::PatchAdmitted { + resolved: ResolvedPatch { + lens_weights: None, + subjects: Vec::new(), + entities: Vec::new(), + routes: Vec::new(), + affordances: Vec::new(), + facts: Vec::new(), + channels: Vec::new(), + operations: vec![ResolvedOp::Transfer { + from: custody.holder, + to: custody.counterparty, + resource: custody.tithe, + qty: Quantity(OPENING_BALANCE + 1), + }], + evidence: Vec::new(), + scale_intent: None, + }, + answers: None, + }; + let error = apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Principal(owner()), + &forged, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_))); + assert_eq!(candidate.holdings, before); + + // The conservation equation is the one owner, and it refuses a ledger + // that does not balance regardless of which operation produced it. + let unbalanced = BTreeMap::from([( + custody.tithe, + LedgerDelta { + before: 7, + after: 9, + admitted: 1, + ..LedgerDelta::default() + }, + )]); + assert_eq!(patch::check_ledger(&unbalanced), Some(custody.tithe)); + let balanced = BTreeMap::from([( + custody.tithe, + LedgerDelta { + before: 7, + after: 8, + admitted: 1, + ..LedgerDelta::default() + }, + )]); + assert_eq!(patch::check_ledger(&balanced), None); + } + + /// Creation of quantity is attributable: an `Admit` whose ref is not in the + /// patch's own evidence list mints nothing and allocates no ID. + #[test] + fn an_admit_without_evidence_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "Unevidenced"); + let topology = admit_topology(&mut kernel); + let speak = speak_entry(&kernel); + let before = kernel.snapshot().unwrap(); + let commits = kernel.journal.commit_count(); + + let mismatches = reject_owner( + &mut kernel, + &before, + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("tithe"), + label: "The Rhythm Tithe".into(), + kind: EntityKind::Resource, + container: None, + }), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("clerk"), + label: "The Ledger Clerk".into(), + kind: SubjectKind::Institution, + controller: NewController::OperationalAgent, + affordances: BTreeSet::from([speak.clone()]), + position: Some(Ref::Existing(topology.yard)), + import_key: None, + }), + ], + operations: vec![ComponentOp::Admit { + holder: Ref::Draft(DraftHandle::new("clerk")), + resource: Ref::Draft(DraftHandle::new("tithe")), + qty: Quantity(4), + evidence: EvidenceRef::new("receipt:never-listed"), + }], + evidence: Vec::new(), + }, + }, + ); + + assert_eq!( + mismatches, + vec![Mismatch::AdmitWithoutEvidence { operation: 0 }] + ); + assert!(kernel.state.holdings.is_empty()); + assert_eq!(kernel.journal.commit_count(), commits); + assert_eq!(kernel.snapshot().unwrap(), before); + } + + #[test] + fn a_transfer_moves_the_exact_quantity_and_nothing_else() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "Transfer"); + let (_, custody, active) = custody_world(&mut kernel); + let entities = kernel.state.entities.clone(); + let edges = kernel.state.edges.clone(); + let positions = kernel.state.positions.clone(); + + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Transfer { + from: Ref::Existing(custody.holder), + to: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(3), + }]), + ); + + assert_eq!(holding(&kernel, custody.holder, custody.tithe), 4); + assert_eq!(holding(&kernel, custody.counterparty, custody.tithe), 3); + assert_eq!(resource_total(&kernel.state, custody.tithe), 7); + assert_eq!(kernel.state.entities, entities); + assert_eq!(kernel.state.edges, edges); + assert_eq!(kernel.state.positions, positions); + } + + /// Absence is zero at both levels, so emptying a holding removes the + /// resource key and emptying a holder removes the holder key. + #[test] + fn consume_reduces_the_holding_and_emptying_removes_the_key() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "Consume"); + let (_, custody, active) = custody_world(&mut kernel); + + let after_three = submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Consume { + holder: Ref::Existing(custody.holder), + resource: Ref::Existing(custody.tithe), + qty: Quantity(3), + }]), + ); + assert!(matches!(after_three, SubmitReceipt::Applied(_))); + assert_eq!(holding(&kernel, custody.holder, custody.tithe), 4); + + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::Consume { + holder: Ref::Existing(custody.holder), + resource: Ref::Existing(custody.tithe), + qty: Quantity(4), + }]), + ); + assert!(!kernel.state.holdings.contains_key(&custody.holder)); + let subject = kernel + .snapshot() + .unwrap() + .subjects + .into_iter() + .find(|subject| subject.id == custody.holder) + .expect("the holder is in the snapshot"); + assert!(subject.components.holdings.is_empty()); + } + + #[test] + fn a_transform_conserves_one_for_one() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "Transform"); + let (_, custody, active) = custody_world(&mut kernel); + + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Transform { + holder: Ref::Existing(custody.holder), + from_resource: Ref::Existing(custody.tithe), + into_resource: Ref::Existing(custody.ingot), + qty: Quantity(5), + }]), + ); + + assert_eq!(holding(&kernel, custody.holder, custody.tithe), 2); + assert_eq!(holding(&kernel, custody.holder, custody.ingot), 5); + assert_eq!(resource_total(&kernel.state, custody.tithe), 2); + assert_eq!(resource_total(&kernel.state, custody.ingot), 5); + } + + #[test] + fn spending_more_than_held_is_rejected_with_insufficient_custody() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "Insufficient"); + let (_, custody, _) = custody_world(&mut kernel); + let too_much = Quantity(OPENING_BALANCE + 1); + let attempts = [ + ComponentOp::Transfer { + from: Ref::Existing(custody.holder), + to: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: too_much, + }, + ComponentOp::Transform { + holder: Ref::Existing(custody.holder), + from_resource: Ref::Existing(custody.tithe), + into_resource: Ref::Existing(custody.ingot), + qty: too_much, + }, + ComponentOp::Consume { + holder: Ref::Existing(custody.holder), + resource: Ref::Existing(custody.tithe), + qty: too_much, + }, + ]; + + for attempt in attempts { + let snapshot = kernel.snapshot().unwrap(); + let commits = kernel.journal.commit_count(); + let mismatches = reject_owner(&mut kernel, &snapshot, operations(vec![attempt])); + assert_eq!( + mismatches, + vec![Mismatch::InsufficientCustody { operation: 0 }] + ); + assert_eq!(kernel.journal.commit_count(), commits); + assert_eq!(kernel.snapshot().unwrap(), snapshot); + } + } + + /// A holder with no entry holds zero: there is no second name for it and no + /// zero entry anywhere in the snapshot. + #[test] + fn an_absent_holding_is_zero() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "Absent"); + let (_, custody, active) = custody_world(&mut kernel); + + let mismatches = reject_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Consume { + holder: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(1), + }]), + ); + assert_eq!( + mismatches, + vec![Mismatch::InsufficientCustody { operation: 0 }] + ); + let counterparty = kernel + .snapshot() + .unwrap() + .subjects + .into_iter() + .find(|subject| subject.id == custody.counterparty) + .expect("the counterparty is in the snapshot"); + assert!(counterparty.components.holdings.is_empty()); + } + + #[test] + fn a_zero_quantity_operation_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "Zero"); + let topology = admit_topology(&mut kernel); + let custody = admit_custody(&mut kernel, &topology); + + // `Admit` is Draft-only, because Active refuses a patch carrying + // evidence, so its zero case is proven before activation. + let draft = kernel.snapshot().unwrap(); + let mismatches = reject_owner( + &mut kernel, + &draft, + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Admit { + holder: Ref::Existing(custody.holder), + resource: Ref::Existing(custody.tithe), + qty: Quantity(0), + evidence: EvidenceRef::new(TITHE_RECEIPT), + }], + evidence: vec![EvidenceRef::new(TITHE_RECEIPT)], + }, + }, + ); + assert_eq!(mismatches, vec![Mismatch::ZeroQuantity { operation: 0 }]); + + let active = activate(&mut kernel); + for attempt in [ + ComponentOp::Transfer { + from: Ref::Existing(custody.holder), + to: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(0), + }, + ComponentOp::Consume { + holder: Ref::Existing(custody.holder), + resource: Ref::Existing(custody.tithe), + qty: Quantity(0), + }, + ] { + let snapshot = kernel.snapshot().unwrap(); + let mismatches = reject_owner(&mut kernel, &snapshot, operations(vec![attempt])); + assert_eq!(mismatches, vec![Mismatch::ZeroQuantity { operation: 0 }]); + } + assert_eq!(kernel.snapshot().unwrap(), active); + } + + #[test] + fn dependency_bind_and_release_round_trip() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "Dependency"); + let (_, custody, active) = custody_world(&mut kernel); + let before = kernel.state.dependencies.clone(); + + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Bind { + subject: Ref::Existing(custody.holder), + target: DependencyRef::Resource(Ref::Existing(custody.tithe)), + }]), + ); + assert_eq!( + kernel.state.dependencies.get(&custody.holder), + Some(&BTreeSet::from([DependencyTarget::Resource(custody.tithe)])) + ); + + let bound = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &bound, + operations(vec![ComponentOp::Release { + subject: Ref::Existing(custody.holder), + target: DependencyRef::Resource(Ref::Existing(custody.tithe)), + }]), + ); + assert_eq!(kernel.state.dependencies, before); + assert!(!kernel.state.dependencies.contains_key(&custody.holder)); + } + + /// A bind that changes nothing is `NoOperationEffect`, the name pass 2 + /// already owns; a subject bound to itself is `SelfDependency`. + #[test] + fn a_duplicate_dependency_bind_is_rejected_as_no_effect() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "Duplicate"); + let (_, custody, active) = custody_world(&mut kernel); + + let bind = ComponentOp::Bind { + subject: Ref::Existing(custody.holder), + target: DependencyRef::Resource(Ref::Existing(custody.tithe)), + }; + submit_owner(&mut kernel, &active, operations(vec![bind.clone()])); + + let bound = kernel.snapshot().unwrap(); + assert_eq!( + reject_owner(&mut kernel, &bound, operations(vec![bind])), + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + assert_eq!( + reject_owner( + &mut kernel, + &bound, + operations(vec![ComponentOp::Release { + subject: Ref::Existing(custody.holder), + target: DependencyRef::Resource(Ref::Existing(custody.ingot)), + }]), + ), + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + assert_eq!( + reject_owner( + &mut kernel, + &bound, + operations(vec![ComponentOp::Bind { + subject: Ref::Existing(custody.holder), + target: DependencyRef::Subject(Ref::Existing(custody.holder)), + }]), + ), + vec![Mismatch::SelfDependency { operation: 0 }] + ); + } + + /// Pass 3 owns the representation of a dependency, not its consequence. A + /// dependency on a closed route commits and shows up in the subject's + /// components; nothing rejects it and nothing fires from it. + #[test] + fn a_dependency_on_a_closed_route_is_representable_and_visible() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "Closed"); + let (topology, custody, active) = custody_world(&mut kernel); + assert!(!kernel.state.edges[&topology.shutter].is_open()); + + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Bind { + subject: Ref::Existing(custody.holder), + target: DependencyRef::Route(Ref::Existing(topology.shutter)), + }]), + ); + + let subject = kernel + .snapshot() + .unwrap() + .subjects + .into_iter() + .find(|subject| subject.id == custody.holder) + .expect("the holder is in the snapshot"); + assert_eq!( + subject.components.dependencies, + BTreeSet::from([DependencyTarget::Route(topology.shutter)]) + ); + } + + /// The digest reads the acting subject's own holdings and dependencies, and + /// only its own: a counterparty's churn does not move it. + #[test] + fn scope_digest_reads_holdings_and_dependencies() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "ScopeCustody"); + let topology = admit_topology(&mut kernel); + let custody = admit_custody(&mut kernel, &topology); + activate(&mut kernel); + let scope = DecisionScope { + subject_id: custody.holder, + }; + let base = scope_digest(&kernel.state, scope).unwrap(); + + let mut spent = kernel.state.clone(); + set_held(&mut spent, custody.holder, custody.tithe, 1); + assert_ne!(scope_digest(&spent, scope).unwrap(), base); + + let mut gained = kernel.state.clone(); + set_held(&mut gained, custody.holder, custody.ingot, 1); + assert_ne!(scope_digest(&gained, scope).unwrap(), base); + + let mut bound = kernel.state.clone(); + bound + .dependencies + .entry(custody.holder) + .or_default() + .insert(DependencyTarget::Resource(custody.tithe)); + assert_ne!(scope_digest(&bound, scope).unwrap(), base); + + let mut elsewhere = kernel.state.clone(); + set_held(&mut elsewhere, custody.counterparty, custody.tithe, 9); + elsewhere + .dependencies + .entry(custody.counterparty) + .or_default() + .insert(DependencyTarget::Resource(custody.ingot)); + assert_eq!(scope_digest(&elsewhere, scope).unwrap(), base); + } + + /// A proposal bound while its subject held seven must not commit after + /// someone took six. Custody churn rejects more bound proposals than route + /// churn did; that is the binding working. + #[test] + fn a_spend_bound_to_a_stale_balance_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "Stale"); + let (_, custody, active) = custody_world(&mut kernel); + let bound = opportunity_for(&active, custody.holder); + + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Transfer { + from: Ref::Existing(custody.holder), + to: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(6), + }]), + ); + + let moved = kernel.snapshot().unwrap(); + let commits = kernel.journal.commit_count(); + let error = kernel + .submit( + command( + &moved, + CommandId::new(), + CallerId::Controller(bound.controller_id), + CommandBody::ExerciseDecision { + opportunity: bound.clone(), + invocation: DecisionInvocation { + affordance: bound.affordance_ids[0], + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Statement::new("The tithe is short.").unwrap()), + display: None, + }, + }, + ), + &AuthenticatedCaller::fixture(CallerId::Controller(bound.controller_id)), + ) + .unwrap_err(); + + assert!(matches!(error, KernelError::ScopeChanged { .. })); + assert_eq!(kernel.journal.commit_count(), commits); + assert_eq!(kernel.snapshot().unwrap(), moved); + } + + /// Soul, proof 4: the ledger equation stated as arithmetic over the + /// committed partitions, across one patch that exercises every conserving + /// operation at once. Per resource, `after == before + admitted + gained - + /// consumed - spent`, and no third resource moves. + #[test] + fn soul_a_mixed_patch_conserves_every_resource_it_touches() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "MixedLedger"); + let (_, custody, active) = custody_world(&mut kernel); + + // The opening balance was created by `Admit` alone: before is zero, + // admitted is the balance, and the total equals the sum of the two. + assert_eq!( + resource_total(&kernel.state, custody.tithe), + u128::from(OPENING_BALANCE) + ); + assert_eq!(resource_total(&kernel.state, custody.ingot), 0); + + let tithe_before = resource_total(&kernel.state, custody.tithe); + let ingot_before = resource_total(&kernel.state, custody.ingot); + + let receipt = submit_owner( + &mut kernel, + &active, + operations(vec![ + ComponentOp::Transfer { + from: Ref::Existing(custody.holder), + to: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(3), + }, + ComponentOp::Transform { + holder: Ref::Existing(custody.holder), + from_resource: Ref::Existing(custody.tithe), + into_resource: Ref::Existing(custody.ingot), + qty: Quantity(2), + }, + ComponentOp::Consume { + holder: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(1), + }, + ]), + ); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + + // Transfer contributes to no term; transform contributes one spent and + // one gained; consume contributes one consumed. Nothing was admitted. + assert_eq!( + resource_total(&kernel.state, custody.tithe), + tithe_before - 1 - 2 + ); + assert_eq!( + resource_total(&kernel.state, custody.ingot), + ingot_before + 2 + ); + assert_eq!(holding(&kernel, custody.holder, custody.tithe), 2); + assert_eq!(holding(&kernel, custody.holder, custody.ingot), 2); + assert_eq!(holding(&kernel, custody.counterparty, custody.tithe), 2); + // Absence is zero: the counterparty never held an ingot, so there is no + // row for one rather than a row holding nothing. + assert!(!kernel.state.holdings[&custody.counterparty].contains_key(&custody.ingot)); + } + + /// Soul: is the apply-side `check_ledger` reachable? + /// + /// A forged `PatchAdmitted` can carry a *sequence* whose second operation + /// exceeds what the first left. It dies at `apply_operation`'s own + /// re-derived precondition, one operation early, so the ledger never speaks. + /// A sequence in which every operation applies cannot break the equation, + /// because every `ResolvedOp` arm debits and credits the same `qty` it + /// records: the apply-side call is unreachable from the current closed set. + #[test] + fn soul_a_forged_sequence_dies_at_the_per_operation_check_not_the_ledger() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "ForgedSequence"); + let (_, custody, _) = custody_world(&mut kernel); + let before = kernel.state.holdings.clone(); + + let forge = |operations: Vec| WorldEffect::PatchAdmitted { + resolved: ResolvedPatch { + lens_weights: None, + subjects: Vec::new(), + entities: Vec::new(), + routes: Vec::new(), + affordances: Vec::new(), + facts: Vec::new(), + channels: Vec::new(), + operations, + evidence: Vec::new(), + scale_intent: None, + }, + answers: None, + }; + let transfer = |qty: u64| ResolvedOp::Transfer { + from: custody.holder, + to: custody.counterparty, + resource: custody.tithe, + qty: Quantity(qty), + }; + + // Two transfers of five out of a balance of seven: the first leaves two, + // the second cannot cover five. + let mut candidate = kernel.state.clone(); + let error = apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Principal(owner()), + &forge(vec![transfer(5), transfer(5)]), + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::Invariant(message) if message == "holder does not hold enough"), + "the per-operation precondition speaks first, not the ledger: {error:?}" + ); + // The candidate is a throwaway clone; the live state never moved. + assert_eq!(kernel.state.holdings, before); + + // Every operation applying means the equation balances, so the same + // forged lane commits a conserving sequence with no ledger complaint. + let mut conserving = kernel.state.clone(); + apply_effect( + &mut conserving, + CommandId::issue(), + &CallerId::Principal(owner()), + &forge(vec![ + transfer(5), + ResolvedOp::Transfer { + from: custody.counterparty, + to: custody.holder, + resource: custody.tithe, + qty: Quantity(5), + }, + ]), + ) + .expect("a conserving forged sequence applies"); + assert_eq!(conserving.holdings, before); + + // The degenerate shapes a forgery could otherwise use to mint or burn + // are refused by the arms themselves, not by the equation. + for degenerate in [ + ResolvedOp::Transfer { + from: custody.holder, + to: custody.holder, + resource: custody.tithe, + qty: Quantity(1), + }, + ResolvedOp::Transform { + holder: custody.holder, + from_resource: custody.tithe, + into_resource: custody.tithe, + qty: Quantity(1), + }, + ] { + let mut candidate = kernel.state.clone(); + let error = apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Principal(owner()), + &forge(vec![degenerate]), + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::Invariant(message) if message == "custody operation moves nothing"), + "unexpected refusal: {error:?}" + ); + } + + // An `Admit` in a forged effect still needs its receipt in the same + // patch, so the apply lane mints no unattributable quantity either. + let mut unevidenced = kernel.state.clone(); + let error = apply_effect( + &mut unevidenced, + CommandId::issue(), + &CallerId::Principal(owner()), + &forge(vec![ResolvedOp::Admit { + holder: custody.holder, + resource: custody.tithe, + qty: Quantity(4), + evidence: EvidenceRef::new(TITHE_RECEIPT), + }]), + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::Invariant(message) if message == "admitted quantity cites no evidence in its patch"), + "unexpected refusal: {error:?}" + ); + assert_eq!(kernel.state.holdings, before); + } + + /// Soul: `QuantityOverflow` is reachable, and the arithmetic that reaches it + /// is `checked_add` rather than a silent clamp. Two admissions in one patch + /// whose sum exceeds `u64::MAX` mint nothing and allocate no ID. + #[test] + fn soul_a_holding_cannot_overflow_silently() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "Overflow"); + let topology = admit_topology(&mut kernel); + let speak = speak_entry(&kernel); + let before = kernel.snapshot().unwrap(); + let commits = kernel.journal.commit_count(); + + let admit = |qty: u64| ComponentOp::Admit { + holder: Ref::Draft(DraftHandle::new("clerk")), + resource: Ref::Draft(DraftHandle::new("tithe")), + qty: Quantity(qty), + evidence: EvidenceRef::new(TITHE_RECEIPT), + }; + let mismatches = reject_owner( + &mut kernel, + &before, + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("tithe"), + label: "The Rhythm Tithe".into(), + kind: EntityKind::Resource, + container: None, + }), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("clerk"), + label: "The Ledger Clerk".into(), + kind: SubjectKind::Institution, + controller: NewController::OperationalAgent, + affordances: BTreeSet::from([speak.clone()]), + position: Some(Ref::Existing(topology.yard)), + import_key: None, + }), + ], + operations: vec![admit(u64::MAX), admit(1)], + evidence: vec![EvidenceRef::new(TITHE_RECEIPT)], + }, + }, + ); + + assert_eq!( + mismatches, + vec![Mismatch::QuantityOverflow { operation: 1 }], + "the overflow is the complete verdict: no clamp, no second name" + ); + assert!(kernel.state.holdings.is_empty()); + assert_eq!(kernel.journal.commit_count(), commits); + assert_eq!(kernel.snapshot().unwrap(), before); + } + + /// Soul, scope: a transfer changes the *receiver's* components too, so the + /// counterparty's in-flight proposal is refused with `ScopeChanged` while an + /// unrelated subject's bound proposal still commits at the later revision. + #[test] + fn soul_an_incoming_transfer_changes_only_the_counterpartys_scope() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "IncomingScope"); + let (topology, custody, active) = custody_world(&mut kernel); + let receiver = opportunity_for(&active, custody.counterparty); + let bystander = opportunity_for(&active, topology.walker); + + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Transfer { + from: Ref::Existing(custody.holder), + to: Ref::Existing(custody.counterparty), + resource: Ref::Existing(custody.tithe), + qty: Quantity(3), + }]), + ); + let moved = kernel.snapshot().unwrap(); + + let exercise = |opportunity: &DecisionOpportunity| CommandBody::ExerciseDecision { + opportunity: opportunity.clone(), + invocation: DecisionInvocation { + affordance: opportunity.affordance_ids[0], + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Statement::new("Counted before the tithe arrived.").unwrap()), + display: None, + }, + }; + + let error = kernel + .submit( + command( + &moved, + CommandId::new(), + CallerId::Controller(receiver.controller_id), + exercise(&receiver), + ), + &AuthenticatedCaller::fixture(CallerId::Controller(receiver.controller_id)), + ) + .unwrap_err(); + assert!( + matches!(error, KernelError::ScopeChanged { .. }), + "the receiver's holdings moved under its bound proposal: {error:?}" + ); + + let receipt = kernel + .submit( + command( + &moved, + CommandId::new(), + CallerId::Controller(bystander.controller_id), + exercise(&bystander), + ), + &AuthenticatedCaller::fixture(CallerId::Controller(bystander.controller_id)), + ) + .expect("an unrelated subject's bound proposal is untouched by the transfer"); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + } +} + +/// Pass 6: `Knowledge`, `Channel`, `Fact` standing, and the non-leakage rule. +/// A subject perceives a speech act if and only if it holds `Knowledge` of that +/// act's fact — the knowledge partition is the sole owner of who-heard-what. +#[cfg(test)] +mod knowledge_tests { + use super::patch::{RefName, Site}; + use super::tests::{ + affordance_named, + FLOOD_EVIDENCE, FLOOD_STATEMENT, Speech, auth_principal, command, creation, operations, + opportunity_for, owner, reject_owner, speech_world, spoken, submit_owner, + }; + use super::*; + use std::path::Path; + + fn speech_kernel(path: &Path, title: &str) -> (WorldKernel, Speech, WorldSnapshot) { + let mut kernel = WorldKernel::create( + path.join("world.cc"), + creation(CommandId::new(), title), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let (speech, active) = speech_world(&mut kernel); + (kernel, speech, active) + } + + fn utter( + kernel: &mut WorldKernel, + snapshot: &WorldSnapshot, + actor: SubjectId, + invocation: DecisionInvocation, + ) -> Result { + let opportunity = opportunity_for(snapshot, actor); + let caller = CallerId::Controller(opportunity.controller_id); + kernel.submit( + command( + snapshot, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + opportunity, + invocation, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + } + + fn say(affordance: AffordanceId, bindings: Vec, text: &str) -> DecisionInvocation { + DecisionInvocation { + affordance, + bindings, + proposed: Vec::new(), + speech: Some(Statement::new(text).unwrap()), + display: None, + } + } + + fn binding(role: &str, target: Target) -> RoleBinding { + RoleBinding { + role: Role(role.into()), + target, + } + } + + fn rejected(result: Result) -> Vec { + match result { + Err(KernelError::ActionRejected(mismatches)) => mismatches, + other => panic!("expected a rejected invocation, got {other:?}"), + } + } + + fn knows(kernel: &WorldKernel, subject: SubjectId, fact: EntityId) -> Option { + kernel + .state + .knowledge + .get(&subject) + .and_then(|held| held.get(&fact)) + .copied() + } + + fn acquire(subject: SubjectId, fact: EntityId, source: AuthoredSource) -> ComponentOp { + ComponentOp::AcquireKnowledge { + subject: Ref::Existing(subject), + fact: Ref::Existing(fact), + source, + confidence: Confidence::Certain, + } + } + + fn minted_claim(kernel: &WorldKernel) -> EntityId { + kernel + .state + .events + .last() + .expect("the committed event") + .speech + .expect("a speech act names its claim") + } + + /// Verification 5, first half: a patch adds knowledge only by citing an + /// accessible fact, and a rejected citation allocates nothing. + #[test] + fn knowledge_citing_an_inaccessible_fact_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "Inaccessible"); + let before = kernel.state.clone(); + + assert_eq!( + reject_owner( + &mut kernel, + &active, + operations(vec![acquire( + speech.listener, + EntityId::issue(), + AuthoredSource::Witnessed + )]), + ), + vec![Mismatch::UnknownCanonical { + site: Site::Operation(0), + expected: RefKind::Entity(EntityKind::Fact), + }] + ); + // A live referent of the wrong kind names the kind it actually is. + assert_eq!( + reject_owner( + &mut kernel, + &active, + operations(vec![acquire( + speech.listener, + speech.hall, + AuthoredSource::Witnessed + )]), + ), + vec![Mismatch::WrongKind { + site: Site::Operation(0), + referent: RefName::Entity(Ref::Existing(speech.hall)), + expected: RefKind::Entity(EntityKind::Fact), + actual: RefKind::Entity(EntityKind::Place), + }] + ); + assert_eq!(kernel.state, before); + + submit_owner( + &mut kernel, + &active, + operations(vec![acquire( + speech.listener, + speech.flood, + AuthoredSource::Witnessed, + )]), + ); + assert_eq!( + knows(&kernel, speech.listener, speech.flood).map(|held| held.source), + Some(KnowledgeSource::Witnessed) + ); + } + + /// Standing is what a fact *is*, so both halves are checked at declaration: + /// canon needs its receipt in the same patch, a claim needs a live asserter. + #[test] + fn a_canonical_fact_needs_evidence_and_a_claim_needs_an_asserter() { + let directory = tempfile::tempdir().unwrap(); + let mut draft = WorldKernel::create( + directory.path().join("world.cc"), + creation(CommandId::new(), "Standing"), + &auth_principal(owner()), + ) + .expect("a draft world") + .0; + let start = draft.snapshot().unwrap(); + let declare = + |standing: FactStandingRef, evidence: Vec| CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("rumour"), + label: "a rumour".into(), + statement: Statement::new("The reeve took two tithes.").unwrap(), + standing, + })], + operations: Vec::new(), + evidence, + }, + }; + + assert_eq!( + reject_owner( + &mut draft, + &start, + declare( + FactStandingRef::Canonical { + evidence: EvidenceRef::new("vault:absent"), + }, + Vec::new(), + ), + ), + vec![Mismatch::FactWithoutEvidence { + handle: DraftHandle::new("rumour"), + }] + ); + assert_eq!( + reject_owner( + &mut draft, + &start, + declare( + FactStandingRef::Claimed { + by: Ref::Draft(DraftHandle::new("nobody")), + }, + Vec::new(), + ), + ), + vec![Mismatch::UnresolvedDraft { + site: Site::Declaration(DraftHandle::new("rumour")), + referent: DraftHandle::new("nobody"), + expected: RefKind::Subject(None), + }] + ); + assert!(draft.state.facts.is_empty()); + + submit_owner( + &mut draft, + &start, + declare( + FactStandingRef::Canonical { + evidence: EvidenceRef::new("vault:rumour"), + }, + vec![EvidenceRef::new("vault:rumour")], + ), + ); + assert_eq!(draft.state.facts.len(), 1); + // The bijection holds in both directions. + let fact = *draft.state.facts.keys().next().unwrap(); + assert_eq!(draft.state.entities[&fact].kind, EntityKind::Fact); + } + + /// A receipt vouches for canon. It cannot vouch for an assertion the kernel + /// never evaluated. + #[test] + fn evidenced_knowledge_of_a_claim_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "Evidenced"); + utter( + &mut kernel, + &active, + speech.speaker, + say( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + "The gate was left open.", + ), + ) + .expect("the proclamation commits"); + let claim = minted_claim(&kernel); + let active = kernel.snapshot().unwrap(); + + assert_eq!( + reject_owner( + &mut kernel, + &active, + operations(vec![acquire( + speech.stranger, + claim, + AuthoredSource::Evidenced + )]), + ), + vec![Mismatch::EvidencedKnowledgeOfClaim { operation: 0 }] + ); + submit_owner( + &mut kernel, + &active, + operations(vec![acquire( + speech.stranger, + speech.flood, + AuthoredSource::Evidenced, + )]), + ); + assert_eq!( + knows(&kernel, speech.stranger, speech.flood).map(|held| held.source), + Some(KnowledgeSource::Evidenced) + ); + assert_eq!( + kernel.state.facts[&speech.flood].standing, + FactStanding::Canonical { + evidence: EvidenceRef::new(FLOOD_EVIDENCE), + } + ); + } + + /// The fan-out is the audience, less the speaker: co-located speech fills + /// the exact room, and the utterance lands in `facts` and nowhere else. + #[test] + fn speak_fans_out_to_the_audience_and_not_beyond() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "FanOut"); + utter( + &mut kernel, + &active, + speech.speaker, + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.listener))], + "Mind the hinge.", + ), + ) + .expect("the whisper commits"); + + let event = kernel.state.events.last().expect("the committed event"); + let claim = event.speech.expect("a speech act names its claim"); + assert_eq!(spoken(&kernel.state, event), Some("Mind the hinge.")); + assert_eq!( + knows(&kernel, speech.listener, claim), + Some(Knowledge { + confidence: Confidence::Believed, + source: KnowledgeSource::Told { + by: speech.speaker, + via: None, + }, + acquired_at: active.revision + 1, + }) + ); + // The yard is inside the hall, but a voice fills a room and not the + // district containing it. The speaker's own claim is not implied. + for outside in [speech.bystander, speech.stranger, speech.speaker] { + assert_eq!(knows(&kernel, outside, claim), None); + } + assert_eq!( + kernel.state.facts[&claim].standing, + FactStanding::Claimed { by: speech.speaker } + ); + // The utterance has exactly one home: a label is a name, not a + // transcript. + assert_ne!(kernel.state.entities[&claim].label, "Mind the hinge."); + } + + /// Co-location is the exact place; a channel's `Reach::Place` is the + /// subtree, through the same containment walk a jurisdiction uses. + #[test] + fn co_location_reach_is_the_exact_place_and_a_channel_place_is_the_subtree() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "Reach"); + utter( + &mut kernel, + &active, + speech.speaker, + say( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + "The horn carries.", + ), + ) + .expect("the proclamation commits"); + let broadcast = minted_claim(&kernel); + assert!(knows(&kernel, speech.listener, broadcast).is_some()); + assert!(knows(&kernel, speech.bystander, broadcast).is_some()); + assert_eq!(knows(&kernel, speech.stranger, broadcast), None); + + // The same speaker's voice reaches only the hall. + let active = kernel.snapshot().unwrap(); + utter( + &mut kernel, + &active, + speech.speaker, + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.listener))], + "A voice does not.", + ), + ) + .expect("the whisper commits"); + let voiced = minted_claim(&kernel); + assert!(knows(&kernel, speech.listener, voiced).is_some()); + assert_eq!(knows(&kernel, speech.bystander, voiced), None); + + // Moving the bystander up the stair puts it in both audiences. + let active = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Relocate { + subject: Ref::Existing(speech.bystander), + via: Ref::Existing(speech.stair), + }]), + ); + let active = kernel.snapshot().unwrap(); + utter( + &mut kernel, + &active, + speech.speaker, + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.bystander))], + "Now you hear it.", + ), + ) + .expect("the whisper commits"); + assert!(knows(&kernel, speech.bystander, minted_claim(&kernel)).is_some()); + } + + /// The delta of a telling is a property of the world, not a defect in the + /// proposal: speaking alone commits the claim and the event and lands + /// nothing. + #[test] + fn speaking_into_an_empty_room_commits_the_claim_and_lands_nothing() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "EmptyRoom"); + let knowledge_before = kernel.state.knowledge.clone(); + utter( + &mut kernel, + &active, + speech.bystander, + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.bystander))], + "Nobody is here.", + ), + ) + .expect("speech into an empty room commits"); + + assert_eq!(kernel.state.knowledge, knowledge_before); + assert_eq!(kernel.state.events.len(), 1); + assert_eq!( + spoken(&kernel.state, kernel.state.events.last().unwrap()), + Some("Nobody is here.") + ); + assert_eq!( + kernel + .state + .facts + .values() + .filter(|record| matches!(record.standing, FactStanding::Claimed { .. })) + .count(), + 1 + ); + } + + + fn show( + affordance: AffordanceId, + bindings: Vec, + speech: Option<&str>, + display: &str, + ) -> DecisionInvocation { + DecisionInvocation { + affordance, + bindings, + proposed: Vec::new(), + speech: speech.map(|text| Statement::new(text).unwrap()), + display: Some(Statement::new(display).unwrap()), + } + } + + /// A visible act is the room's to see and nobody else's: everyone standing + /// in the actor's place holds it as `Seen { by }`; the actor, the yard + /// below, and the placeless hold nothing. The entry's own audience is not + /// consulted: a proclamation down the horn carries its words to the yard + /// and still folds its arms only before the hall. + #[test] + fn a_display_is_seen_by_the_room_and_by_no_one_else() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "Display"); + utter( + &mut kernel, + &active, + speech.speaker, + show( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + Some("The horn carries."), + "I fold my arms.", + ), + ) + .expect("the proclamation with a display commits"); + + let event = kernel.state.events.last().expect("the committed event"); + let said = event.speech.expect("the utterance names its claim"); + let seen = event.display.expect("the display names its claim"); + assert_ne!(said, seen); + assert_eq!(kernel.state.facts[&seen].statement.as_str(), "I fold my arms."); + assert_eq!( + kernel.state.facts[&seen].standing, + FactStanding::Claimed { by: speech.speaker } + ); + assert!(knows(&kernel, speech.bystander, said).is_some()); + assert_eq!( + knows(&kernel, speech.listener, seen), + Some(Knowledge { + confidence: Confidence::Believed, + source: KnowledgeSource::Seen { by: speech.speaker }, + acquired_at: active.revision + 1, + }) + ); + for blind in [speech.bystander, speech.stranger, speech.speaker] { + assert_eq!(knows(&kernel, blind, seen), None); + } + // One act minted both claims, so the listener's snapshot stamps both + // rows with the one revision, and the operator's feed carries both. + let snapshot = kernel.snapshot().unwrap(); + let listener = snapshot + .subjects + .iter() + .find(|subject| subject.id == speech.listener) + .unwrap(); + let stamps: BTreeSet> = listener + .knowledge + .iter() + .filter(|row| row.fact == said || row.fact == seen) + .map(|row| row.minted_at) + .collect(); + assert_eq!(stamps, BTreeSet::from([Some(event.revision)])); + let log = kernel.operator_log().unwrap(); + assert_eq!(log.last().unwrap().speech.as_ref().unwrap().as_str(), "The horn carries."); + assert_eq!(log.last().unwrap().display.as_ref().unwrap().as_str(), "I fold my arms."); + } + + /// A silent turn: the kernel `speak` entry invoked with no utterance and a + /// display is an address, not `SpeechRequired`. The act lands, no speech + /// claim is minted, and alone in the yard the same act commits its claim + /// and lands nothing, as speaking alone does. + #[test] + fn a_silent_display_addresses_the_room_through_the_speak_entry() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "Silent"); + let speak = affordance_named(&active, "speak"); + utter( + &mut kernel, + &active, + speech.speaker, + show(speak, Vec::new(), None, "I nod toward the stair."), + ) + .expect("a silent act commits"); + let event = kernel.state.events.last().unwrap(); + assert!(event.speech.is_none()); + let seen = event.display.expect("the display names its claim"); + assert_eq!( + knows(&kernel, speech.listener, seen).map(|held| held.source), + Some(KnowledgeSource::Seen { by: speech.speaker }) + ); + assert_eq!(claimed(&kernel), 1); + + let active = kernel.snapshot().unwrap(); + let knowledge_before = kernel.state.knowledge.clone(); + utter( + &mut kernel, + &active, + speech.bystander, + show(speak, Vec::new(), None, "I sit on the step."), + ) + .expect("a display into an empty room commits"); + assert_eq!(kernel.state.knowledge, knowledge_before); + assert_eq!(kernel.state.events.len(), 2); + assert_eq!(claimed(&kernel), 2); + } + + /// The refusals, each at its own layer: a padded act is `EmptyDisplay` at + /// the check; a speech-carrying entry given neither words nor act is + /// `SpeechRequired`; the placeless stranger has no room to be seen in and + /// fails the entry's own `NoAudience`. None of them mints anything. + #[test] + fn a_display_is_refused_when_empty_placeless_or_when_nothing_is_addressed() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "Refused"); + let speak = affordance_named(&active, "speak"); + let mut padded = show(speak, Vec::new(), None, "placeholder"); + padded.display = Some(serde_json::from_str::("\" \"").unwrap()); + assert_eq!( + rejected(utter(&mut kernel, &active, speech.speaker, padded)), + vec![ActionMismatch::EmptyDisplay] + ); + let mute = DecisionInvocation { + affordance: speech.whisper, + bindings: vec![binding("target", Target::Subject(speech.listener))], + proposed: Vec::new(), + speech: None, + display: None, + }; + assert_eq!( + rejected(utter(&mut kernel, &active, speech.speaker, mute)), + vec![ActionMismatch::SpeechRequired] + ); + assert_eq!( + rejected(utter( + &mut kernel, + &active, + speech.stranger, + show(speak, Vec::new(), None, "I shrug."), + )), + vec![ActionMismatch::NoAudience { precondition: 0 }] + ); + assert!(kernel.state.events.is_empty()); + assert_eq!(claimed(&kernel), 0); + } + + /// The claims a display minted, its `Seen` rows, and its event replay from + /// the journal exactly, through the same path as speech. + #[test] + fn restart_replay_after_a_display_is_exact() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (speech, world_id, expected) = { + let mut kernel = WorldKernel::create( + &path, + creation(CommandId::new(), "ReplayDisplay"), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let (speech, active) = speech_world(&mut kernel); + let speak = affordance_named(&active, "speak"); + utter( + &mut kernel, + &active, + speech.speaker, + show(speak, Vec::new(), Some("One."), "I raise one finger."), + ) + .expect("the act commits"); + let active = kernel.snapshot().unwrap(); + utter( + &mut kernel, + &active, + speech.listener, + show(speak, Vec::new(), None, "I look away."), + ) + .expect("the silent act commits"); + (speech, kernel.state.world_id, kernel.state.clone()) + }; + let reopened = WorldKernel::open(&path, world_id).expect("the store replays"); + assert_eq!(reopened.state, expected); + assert!(reopened.state.knowledge[&speech.listener] + .values() + .any(|held| held.source == KnowledgeSource::Seen { by: speech.speaker })); + assert!(reopened.state.knowledge[&speech.speaker] + .values() + .any(|held| held.source == KnowledgeSource::Seen { by: speech.listener })); + } + + fn claimed(kernel: &WorldKernel) -> usize { + kernel + .state + .facts + .values() + .filter(|record| matches!(record.standing, FactStanding::Claimed { .. })) + .count() + } + + /// The horn belongs to the temple: its controller may speak on it whether + /// or not it stands inside its reach, and removing the controller flips the + /// same invocation to exactly one named failure. + #[test] + fn a_channel_controller_may_speak_outside_its_own_reach() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "Controller"); + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::SetReach { + channel: Ref::Existing(speech.horn), + reach: ReachRef::Subjects(BTreeSet::from([Ref::Existing(speech.listener)])), + }]), + ); + let proclaim = || { + say( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + "The horn still carries.", + ) + }; + let active = kernel.snapshot().unwrap(); + utter(&mut kernel, &active, speech.speaker, proclaim()) + .expect("the controller may speak on its own channel"); + + let active = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::SetController { + channel: Ref::Existing(speech.horn), + controller: None, + }]), + ); + let active = kernel.snapshot().unwrap(); + assert_eq!( + rejected(utter(&mut kernel, &active, speech.speaker, proclaim())), + vec![ActionMismatch::NoAudience { precondition: 0 }] + ); + } + + /// Addressing does not narrow the audience, and a target outside it names + /// itself. A target that walked in mid-flight commits, and the whole + /// audience receives the telling, not only the addressed subject. + #[test] + fn an_addressed_subject_outside_the_audience_names_itself() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "Addressing"); + let whisper = || { + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.bystander))], + "Come inside.", + ) + }; + assert_eq!( + rejected(utter(&mut kernel, &active, speech.speaker, whisper())), + vec![ActionMismatch::CannotReach { precondition: 0 }] + ); + + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Relocate { + subject: Ref::Existing(speech.bystander), + via: Ref::Existing(speech.stair), + }]), + ); + let active = kernel.snapshot().unwrap(); + utter(&mut kernel, &active, speech.speaker, whisper()) + .expect("the addressed subject is now in the room"); + let claim = minted_claim(&kernel); + assert!(knows(&kernel, speech.bystander, claim).is_some()); + assert!( + knows(&kernel, speech.listener, claim).is_some(), + "speaking to someone in a room is heard by the room" + ); + } + + /// `Knows` compares confidence with one `>=`, and `Forget` removes the key + /// rather than storing a zero. + #[test] + fn knows_fails_below_its_confidence_and_forget_removes() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "Knows"); + let recant = || DecisionInvocation { + affordance: speech.recant, + bindings: vec![binding("fact", Target::Entity(speech.flood))], + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + speech: None, + display: None, + }; + assert_eq!( + rejected(utter(&mut kernel, &active, speech.listener, recant())), + vec![ActionMismatch::FactUnknown { precondition: 0 }] + ); + + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::AcquireKnowledge { + subject: Ref::Existing(speech.listener), + fact: Ref::Existing(speech.flood), + source: AuthoredSource::Witnessed, + confidence: Confidence::Believed, + }]), + ); + let active = kernel.snapshot().unwrap(); + assert_eq!( + rejected(utter(&mut kernel, &active, speech.listener, recant())), + vec![ActionMismatch::FactUnknown { precondition: 0 }], + "Believed falls short of Certain" + ); + + submit_owner( + &mut kernel, + &active, + operations(vec![acquire( + speech.listener, + speech.flood, + AuthoredSource::Witnessed, + )]), + ); + let active = kernel.snapshot().unwrap(); + utter(&mut kernel, &active, speech.listener, recant()) + .expect("certainty admits the recant"); + // Absence is the one shape of knowing nothing: no empty inner map. + assert!(!kernel.state.knowledge.contains_key(&speech.listener)); + + let active = kernel.snapshot().unwrap(); + assert_eq!( + reject_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Forget { + subject: Ref::Existing(speech.listener), + fact: Ref::Existing(speech.flood), + }]), + ), + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + } + + /// A telling never overwrites and never downgrades: the knower owns its own + /// credence. + #[test] + fn a_telling_never_overwrites_a_holder() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "NoOverwrite"); + submit_owner( + &mut kernel, + &active, + operations(vec![acquire( + speech.listener, + speech.flood, + AuthoredSource::Witnessed, + )]), + ); + let before = knows(&kernel, speech.listener, speech.flood); + let active = kernel.snapshot().unwrap(); + + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Communicate { + speaker: Ref::Existing(speech.speaker), + fact: Ref::Existing(speech.flood), + to: AudienceRef::Channel(Ref::Existing(speech.horn)), + }]), + ); + assert_eq!(knows(&kernel, speech.listener, speech.flood), before); + assert_eq!( + knows(&kernel, speech.bystander, speech.flood), + Some(Knowledge { + confidence: Confidence::Believed, + source: KnowledgeSource::Told { + by: speech.speaker, + via: Some(speech.horn), + }, + acquired_at: active.revision + 1, + }) + ); + } + + /// Ontology admission: communication reaches only subjects inside the + /// channel's reach, and a speaker outside it is not speaking. + #[test] + fn communicating_from_outside_the_audience_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "OutsideAudience"); + assert_eq!( + reject_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Communicate { + speaker: Ref::Existing(speech.stranger), + fact: Ref::Existing(speech.flood), + to: AudienceRef::Colocated, + }]), + ), + vec![Mismatch::SpeakerOutsideAudience { operation: 0 }] + ); + assert_eq!( + reject_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Communicate { + speaker: Ref::Existing(speech.stranger), + fact: Ref::Existing(speech.flood), + to: AudienceRef::Channel(Ref::Existing(speech.horn)), + }]), + ), + vec![Mismatch::SpeakerOutsideAudience { operation: 0 }] + ); + assert!(kernel.state.knowledge.is_empty()); + } + + /// The two allocation sites, asserted: only `derive_id` allocates, and the + /// action lane's one referent per invocation is reproduced by calling it + /// directly with the recorded world, command, handle, and discriminator. + #[test] + fn every_canonical_id_comes_from_one_of_two_sites() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "Allocation"); + let world_id = kernel.state.world_id; + let command_id = CommandId::new(); + let opportunity = opportunity_for(&active, speech.speaker); + let caller = CallerId::Controller(opportunity.controller_id); + let entities_before = kernel.state.entities.len(); + kernel + .submit( + command( + &active, + command_id, + caller.clone(), + CommandBody::ExerciseDecision { + opportunity, + invocation: say( + speech.whisper, + vec![binding("target", Target::Subject(speech.listener))], + "Counted.", + ), + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .expect("the whisper commits"); + + let claim = minted_claim(&kernel); + assert_eq!( + claim, + EntityId(patch::derive_id( + patch::ENTITY_NAMESPACE, + world_id, + command_id, + &DraftHandle::new("ghostlight.speech"), + Some("0"), + )) + ); + // Exactly one referent, always a fact, always claimed by the actor. + assert_eq!(kernel.state.entities.len(), entities_before + 1); + assert_eq!(kernel.state.entities[&claim].kind, EntityKind::Fact); + assert_eq!( + kernel.state.facts[&claim].standing, + FactStanding::Claimed { by: speech.speaker } + ); + } + + /// Replay is exact because every allocation derives from committed inputs + /// and every fan-out is re-derived at apply from the audience plus live + /// state. + #[test] + fn restart_replay_after_speech_is_exact() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (speech, world_id, expected) = { + let mut kernel = WorldKernel::create( + &path, + creation(CommandId::new(), "ReplaySpeech"), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let (speech, active) = speech_world(&mut kernel); + utter( + &mut kernel, + &active, + speech.speaker, + say( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + "One.", + ), + ) + .expect("the first proclamation commits"); + let active = kernel.snapshot().unwrap(); + utter( + &mut kernel, + &active, + speech.listener, + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.speaker))], + "Two.", + ), + ) + .expect("the whisper commits"); + let active = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Communicate { + speaker: Ref::Existing(speech.speaker), + fact: Ref::Existing(speech.flood), + to: AudienceRef::Channel(Ref::Existing(speech.horn)), + }]), + ); + let world_id = kernel.state.world_id; + (speech, world_id, kernel.state.clone()) + }; + + let reopened = WorldKernel::open(&path, world_id).expect("the store replays"); + assert_eq!(reopened.state.facts, expected.facts); + assert_eq!(reopened.state.channels, expected.channels); + assert_eq!(reopened.state.knowledge, expected.knowledge); + assert_eq!(reopened.state.events, expected.events); + assert_eq!(reopened.state, expected); + assert!(!reopened.state.knowledge[&speech.bystander].is_empty()); + } + + /// A forged claim does not apply, and a forged recipient list is + /// unrepresentable: `ResolvedOp::Communicate` stores an audience, never + /// recipients. + #[test] + fn a_forged_claim_or_forged_recipient_does_not_apply() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "Forgery"); + let command_id = CommandId::new(); + let opportunity = opportunity_for(&active, speech.speaker); + let caller = CallerId::Controller(opportunity.controller_id); + let invocation = say( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + "Honest.", + ); + let granted = require_granted(&kernel.state, &opportunity, invocation.affordance).unwrap(); + let honest = action::exercise( + &kernel.state, + command_id, + &opportunity, + &granted, + &invocation, + ) + .expect("the honest event derives"); + let fact = honest.speech.expect("the honest claim"); + + let mut forged_claim = honest.clone(); + forged_claim.speech = Some(speech.flood); + let mut forged_statement = honest.clone(); + forged_statement.effects[0] = ResolvedOp::AssertClaim { + fact, + statement: Statement::new("Forged.").unwrap(), + by: speech.speaker, + }; + let mut forged_asserter = honest.clone(); + forged_asserter.effects[0] = ResolvedOp::AssertClaim { + fact, + statement: Statement::new("Honest.").unwrap(), + by: speech.listener, + }; + for forged in [forged_claim, forged_statement, forged_asserter] { + let mut candidate = kernel.state.clone(); + let error = apply_effect( + &mut candidate, + command_id, + &caller, + &WorldEffect::DecisionExercised { + opportunity: opportunity.clone(), + invocation: invocation.clone(), + event: forged, + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_))); + assert_eq!(candidate, kernel.state); + } + + // A recipient list cannot be forged because none is stored. + assert!(matches!( + honest.effects[1], + ResolvedOp::Communicate { + to: Audience::Channel(_), + .. + } + )); + let mut candidate = kernel.state.clone(); + apply_effect( + &mut candidate, + command_id, + &caller, + &WorldEffect::DecisionExercised { + opportunity, + invocation, + event: honest, + }, + ) + .expect("the honest event applies"); + assert!(candidate.knowledge.contains_key(&speech.listener)); + } + + /// The scope table: a telling rebinds its listener and leaves a bystander + /// alone, and a reach change moves only the controller's digest. + #[test] + fn a_telling_moves_only_the_listeners_scope() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "ScopeMove"); + let digest = |kernel: &WorldKernel, subject: SubjectId| { + scope_digest( + &kernel.state, + DecisionScope { + subject_id: subject, + }, + ) + .unwrap() + }; + let listener_before = digest(&kernel, speech.listener); + let bystander_before = digest(&kernel, speech.bystander); + + utter( + &mut kernel, + &active, + speech.speaker, + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.listener))], + "Only you.", + ), + ) + .expect("the whisper commits"); + assert_ne!(digest(&kernel, speech.listener), listener_before); + assert_eq!(digest(&kernel, speech.bystander), bystander_before); + + // Reach membership is admission-only: adding a hearer moves the + // controller's digest and nobody else's. + let active = kernel.snapshot().unwrap(); + let hearer_before = digest(&kernel, speech.listener); + let speaker_before = digest(&kernel, speech.speaker); + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::SetReach { + channel: Ref::Existing(speech.horn), + reach: ReachRef::Subjects(BTreeSet::from([Ref::Existing(speech.stranger)])), + }]), + ); + assert_eq!(digest(&kernel, speech.listener), hearer_before); + assert_ne!(digest(&kernel, speech.speaker), speaker_before); + } + + /// A speech-carrying entry names exactly one audience: none is unlowerable + /// and two is unchoosable. Each rejection allocates no `AffordanceId`. + #[test] + fn a_speech_carrying_entry_must_declare_exactly_one_audience() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = WorldKernel::create( + directory.path().join("world.cc"), + creation(CommandId::new(), "SpeechAudience"), + &auth_principal(owner()), + ) + .expect("a draft world") + .0; + let before = kernel.snapshot().unwrap(); + let catalog_before = kernel.state.affordance_catalog.len(); + let declare = |preconditions: Vec| CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("herald"), + kind: AffordanceKindName("herald".into()), + roles: Vec::new(), + preconditions, + effect_slots: Vec::new(), + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + carries_speech: true, + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }; + assert_eq!( + reject_owner(&mut kernel, &before, declare(Vec::new())), + vec![Mismatch::SpeechWithoutAudience { + handle: DraftHandle::new("herald"), + }] + ); + assert_eq!( + reject_owner( + &mut kernel, + &before, + declare(vec![ + Precondition::CanBroadcast { + via: AudienceSpec::Colocated, + }, + Precondition::CanBroadcast { + via: AudienceSpec::Colocated, + }, + ]), + ), + vec![Mismatch::AmbiguousSpeechAudience { + handle: DraftHandle::new("herald"), + }] + ); + assert_eq!(kernel.state.affordance_catalog.len(), catalog_before); + } + + /// The kernel does not compare two statements: no dedup, no interning, no + /// contradiction check, no similarity. A claim byte-identical to a + /// canonical fact and one that plainly negates it commit identically. + #[test] + fn the_kernel_never_compares_two_statements() { + let directory = tempfile::tempdir().unwrap(); + let run = |name: &str, text: &str| { + let room = directory.path().join(name); + std::fs::create_dir_all(&room).unwrap(); + let (mut kernel, speech, active) = speech_kernel(&room, name); + let receipt = utter( + &mut kernel, + &active, + speech.speaker, + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.listener))], + text, + ), + ) + .expect("both statements commit identically"); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + let event = kernel.state.events.last().unwrap().clone(); + (kernel, speech, event) + }; + let (agreeing, agreeing_speech, agreeing_event) = run("agree", FLOOD_STATEMENT); + let (negating, _, negating_event) = run("negate", "The lower hinge is dry."); + + assert_eq!(agreeing_event.band, negating_event.band); + assert_eq!(agreeing_event.effects.len(), negating_event.effects.len()); + assert_eq!(agreeing.state.facts.len(), negating.state.facts.len()); + // Two facts with byte-identical statements are two facts: the claim is + // not the canonical fact it repeats, and neither run learned anything + // about the other's meaning. + let claim = agreeing_event.speech.unwrap(); + assert_ne!(claim, agreeing_speech.flood); + assert_eq!( + agreeing.state.facts[&claim].statement, + agreeing.state.facts[&agreeing_speech.flood].statement + ); + assert_ne!( + agreeing.state.facts[&claim].standing, + agreeing.state.facts[&agreeing_speech.flood].standing + ); + } +} + +/// Soul's pass-6 falsification set. Each test names the claim it attacks and, +/// where the landed behaviour differs from the specified one, pins the actual +/// behaviour so the difference is visible rather than assumed. +#[cfg(test)] +mod soul_knowledge_tests { + use super::tests::{ + FLOOD_STATEMENT, Speech, affordance_named, auth_principal, command, creation, operations, + opportunity_for, owner, speech_world, submit_owner, + }; + use super::*; + use std::path::Path; + + fn speech_kernel(path: &Path, title: &str) -> (WorldKernel, Speech, WorldSnapshot) { + let mut kernel = WorldKernel::create( + path.join("world.cc"), + creation(CommandId::new(), title), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let (speech, active) = speech_world(&mut kernel); + (kernel, speech, active) + } + + fn say(affordance: AffordanceId, bindings: Vec, text: &str) -> DecisionInvocation { + DecisionInvocation { + affordance, + bindings, + proposed: Vec::new(), + speech: Some(Statement::new(text).unwrap()), + display: None, + } + } + + fn binding(role: &str, target: Target) -> RoleBinding { + RoleBinding { + role: Role(role.into()), + target, + } + } + + fn utter( + kernel: &mut WorldKernel, + snapshot: &WorldSnapshot, + actor: SubjectId, + invocation: DecisionInvocation, + ) -> Result { + let opportunity = opportunity_for(snapshot, actor); + let caller = CallerId::Controller(opportunity.controller_id); + kernel.submit( + command( + snapshot, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + opportunity, + invocation, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + } + + fn knows(kernel: &WorldKernel, subject: SubjectId, fact: EntityId) -> Option { + kernel + .state + .knowledge + .get(&subject) + .and_then(|held| held.get(&fact)) + .copied() + } + + fn digest_of(kernel: &WorldKernel, subject_id: SubjectId) -> ScopeDigest { + scope_digest(&kernel.state, DecisionScope { subject_id }).unwrap() + } + + fn minted_claim(kernel: &WorldKernel) -> EntityId { + kernel + .state + .events + .last() + .expect("the committed event") + .speech + .expect("a speech act names its claim") + } + + /// A channel's controller carries exactly one privilege: `can_broadcast` + /// lets it sound the horn from outside the declared reach. `audience` + /// itself never folds the controller in, so the controller is not a + /// recipient of a telling it did not stand inside, whether the telling is + /// its own or another subject's. + #[test] + fn soul_a_channel_controller_hears_what_it_is_out_of_reach_of() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "ControllerHears"); + // The horn now reaches exactly one subject. The speaker controls it and + // is not in that set. + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::SetReach { + channel: Ref::Existing(speech.horn), + reach: ReachRef::Subjects(BTreeSet::from([Ref::Existing(speech.listener)])), + }]), + ); + let active = kernel.snapshot().unwrap(); + assert_eq!( + kernel.state.channels[&speech.horn].reach, + Reach::Subjects(BTreeSet::from([speech.listener])) + ); + + // The controller may still speak from outside its own reach — the horn + // belongs to the temple — and the listener, who stands inside the + // reach, hears it. + utter( + &mut kernel, + &active, + speech.speaker, + say( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + "The horn is mine to sound.", + ), + ) + .expect("the controller may speak on its own channel"); + let controllers_claim = minted_claim(&kernel); + assert_eq!( + knows(&kernel, speech.listener, controllers_claim), + Some(Knowledge { + confidence: Confidence::Believed, + source: KnowledgeSource::Told { + by: speech.speaker, + via: Some(speech.horn), + }, + acquired_at: active.revision + 1, + }) + ); + // The controller gains no knowledge of its own claim: it is outside + // the reach, and speaking privilege is not audience membership. + assert_eq!(knows(&kernel, speech.speaker, controllers_claim), None); + + // Now the listener speaks on the same channel. + let active = kernel.snapshot().unwrap(); + utter( + &mut kernel, + &active, + speech.listener, + say( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + "The horn is mine tonight.", + ), + ) + .expect("a subject inside the reach may broadcast"); + let claim = minted_claim(&kernel); + + // The declared reach names the listener alone, and the listener spoke, + // so the declared fan-out is empty. The controller — outside the + // reach, and not the speaker this time either — learns nothing. + assert_eq!( + knows(&kernel, speech.speaker, claim), + None, + "the controller does not gain knowledge through fan-out" + ); + assert_eq!(knows(&kernel, speech.bystander, claim), None); + assert_eq!(knows(&kernel, speech.stranger, claim), None); + assert_eq!(knows(&kernel, speech.listener, claim), None); + } + + /// Every speech precondition fails at `exercise`, before the band draw and + /// before the speech lowering, so a refused utterance mints no claim and + /// leaves the whole committed state byte-identical. Nothing here reaches + /// replay to be caught later. + #[test] + fn soul_a_refused_utterance_dies_at_the_gate_and_allocates_nothing() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "GateNotReplay"); + let speak = affordance_named(&active, "speak"); + let before = kernel.state.clone(); + + let cases: Vec<(SubjectId, DecisionInvocation, Vec)> = vec![ + // Unplaced: no co-location audience at all. + ( + speech.stranger, + say(speak, Vec::new(), "Anyone?"), + vec![ActionMismatch::NoAudience { precondition: 0 }], + ), + // Addressed at a subject one containment level down. + ( + speech.speaker, + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.bystander))], + "Down there.", + ), + vec![ActionMismatch::CannotReach { precondition: 0 }], + ), + // `recant` requires `Knows { at_least: Certain }` of the bound fact. + // Its unproposed slot names itself beside the precondition; the + // point is that the complete set lands at the gate, in one pass. + ( + speech.speaker, + DecisionInvocation { + affordance: speech.recant, + bindings: vec![binding("fact", Target::Entity(speech.flood))], + proposed: Vec::new(), + speech: None, + display: None, + }, + vec![ + ActionMismatch::SlotNotProposed { slot: 0 }, + ActionMismatch::FactUnknown { precondition: 0 }, + ], + ), + ]; + + for (actor, invocation, expected) in cases { + let error = utter(&mut kernel, &active, actor, invocation).unwrap_err(); + let KernelError::ActionRejected(mismatches) = error else { + panic!("expected an action rejection, got {error:?}"); + }; + assert_eq!(mismatches, expected); + // No claim, no entity row, no event, no revision: the gate ran + // before anything was drawn or lowered. + assert_eq!(kernel.state, before); + } + } + + /// Fan-out is the sole way knowledge enters another subject from speech, and + /// it is not carried by the effect. A forged `DecisionExercised` that widens + /// the audience, appends a second telling, or tells a foreign fact is refused + /// by `apply_effect` itself, so replay is never the first reader to notice. + #[test] + fn soul_a_forged_wider_audience_does_not_apply() { + let directory = tempfile::tempdir().unwrap(); + let (kernel, speech, active) = speech_kernel(directory.path(), "WiderAudience"); + let command_id = CommandId::new(); + let opportunity = opportunity_for(&active, speech.speaker); + let caller = CallerId::Controller(opportunity.controller_id); + let invocation = say( + speech.whisper, + vec![binding("target", Target::Subject(speech.listener))], + "Only the hall.", + ); + let granted = require_granted(&kernel.state, &opportunity, invocation.affordance).unwrap(); + let honest = action::exercise( + &kernel.state, + command_id, + &opportunity, + &granted, + &invocation, + ) + .expect("the honest event derives"); + let fact = honest.speech.expect("the honest claim"); + assert_eq!( + honest.effects[1], + ResolvedOp::Communicate { + speaker: speech.speaker, + fact, + to: Audience::Colocated, + } + ); + + // Widened to the horn, which covers the yard through `covers_place`. + let mut widened = honest.clone(); + widened.effects[1] = ResolvedOp::Communicate { + speaker: speech.speaker, + fact, + to: Audience::Channel(speech.horn), + }; + // A second telling appended to the same event. + let mut doubled = honest.clone(); + doubled.effects.push(ResolvedOp::Communicate { + speaker: speech.speaker, + fact: speech.flood, + to: Audience::Colocated, + }); + // A telling of a fact this act did not mint. + let mut foreign = honest.clone(); + foreign.effects[1] = ResolvedOp::Communicate { + speaker: speech.speaker, + fact: speech.flood, + to: Audience::Colocated, + }; + + for forged in [widened, doubled, foreign] { + let mut candidate = kernel.state.clone(); + let error = apply_effect( + &mut candidate, + command_id, + &caller, + &WorldEffect::DecisionExercised { + opportunity: opportunity.clone(), + invocation: invocation.clone(), + event: forged, + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_))); + assert_eq!(candidate, kernel.state); + } + } + + /// A speech act that lands nothing moves no digest at all, the speaker's own + /// included. `AssertClaim` writes `entities` and `facts`, and neither is a + /// scope component, so an in-flight proposal held by anyone in the world + /// survives an utterance nobody heard. + #[test] + fn soul_speech_that_lands_nothing_moves_no_digest_including_the_speakers() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "NoDigestMove"); + let speak = affordance_named(&active, "speak"); + let everyone = [ + speech.speaker, + speech.listener, + speech.bystander, + speech.stranger, + ]; + let before: Vec = everyone + .iter() + .map(|subject| digest_of(&kernel, *subject)) + .collect(); + let facts_before = kernel.state.facts.len(); + + // The bystander stands alone in the yard. + utter( + &mut kernel, + &active, + speech.bystander, + say(speak, Vec::new(), "Nobody is here."), + ) + .expect("speaking into an empty room commits"); + + assert_eq!(kernel.state.facts.len(), facts_before + 1); + assert_eq!(kernel.state.events.len(), 1); + assert!(kernel.state.knowledge.is_empty()); + for (subject, digest) in everyone.iter().zip(before) { + assert_eq!( + digest_of(&kernel, *subject), + digest, + "an utterance nobody heard moved a scope digest" + ); + } + } + + /// The resolver does not model a `Communicate`'s fan-out, so a same-patch + /// telling followed by a `Forget` of what that telling would have landed is + /// refused at resolve although apply would accept it. The asymmetry is + /// fail-closed, and it does not refuse the order that must work: forgetting + /// first and being told again in the same patch commits, and the telling is + /// what the subject ends up holding. + #[test] + fn soul_a_same_patch_telling_then_forget_fails_closed_only() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "SamePatchOrder"); + let tell = ComponentOp::Communicate { + speaker: Ref::Existing(speech.speaker), + fact: Ref::Existing(speech.flood), + to: AudienceRef::Colocated, + }; + let forget = ComponentOp::Forget { + subject: Ref::Existing(speech.listener), + fact: Ref::Existing(speech.flood), + }; + + let error = kernel + .submit( + command( + &active, + CommandId::new(), + CallerId::Principal(owner()), + operations(vec![tell.clone(), forget.clone()]), + ), + &auth_principal(owner()), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch, got {error:?}"); + }; + assert_eq!( + mismatches, + vec![Mismatch::NoOperationEffect { operation: 1 }] + ); + + // The legitimate order. The listener holds the fact first, forgets it, + // and the telling in the same patch lands it again as a telling, which + // is what the committed state carries. + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::AcquireKnowledge { + subject: Ref::Existing(speech.listener), + fact: Ref::Existing(speech.flood), + source: AuthoredSource::Witnessed, + confidence: Confidence::Certain, + }]), + ); + let active = kernel.snapshot().unwrap(); + submit_owner(&mut kernel, &active, operations(vec![forget, tell])); + assert_eq!( + knows(&kernel, speech.listener, speech.flood), + Some(Knowledge { + confidence: Confidence::Believed, + source: KnowledgeSource::Told { + by: speech.speaker, + via: None, + }, + acquired_at: active.revision + 1, + }) + ); + } + + /// `verify_state_shape` checks the forward speech direction only: an event's + /// claim is asserted by the acting subject and named by no other event. The + /// reverse, that every claim is named by some event, is deliberately absent, + /// because a world may declare a claim in Draft with no event behind it. + /// That gap is not a hole: active admission refuses every declaration, so + /// `AssertClaim` is the only way a claim enters an active world and it is + /// synthesized with its event. + #[test] + fn soul_an_orphan_claim_is_a_draft_shape_and_unreachable_in_active() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "OrphanClaim"); + // The Draft-declared fact is an orphan by construction: no event names + // it. Reopening runs the shape verifier over the replayed state. + assert!(kernel.state.facts.contains_key(&speech.flood)); + assert!( + kernel + .state + .events + .iter() + .all(|event| event.speech.is_none()) + ); + let world_id = kernel.state.world_id; + + let before = kernel.state.clone(); + let error = kernel + .submit( + command( + &active, + CommandId::new(), + CallerId::Principal(owner()), + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("rumour"), + label: "a rumour".into(), + statement: Statement::new("The gate is unguarded.").unwrap(), + standing: FactStandingRef::Claimed { + by: Ref::Existing(speech.speaker), + }, + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ), + &auth_principal(owner()), + ) + .unwrap_err(); + assert!( + matches!(error, KernelError::AnswerRequired), + "an active world admitted an unanswered declaration: {error:?}" + ); + assert_eq!(kernel.state, before); + drop(kernel); + let replayed = WorldKernel::open(&path, world_id).expect("the orphan store is healthy"); + assert_eq!(replayed.state.facts, before.facts); + } + + /// Replay equality across every new arm, twice, with no RNG and no clock in + /// any of them: a speech act, a telling, an authored acquisition, a forget, + /// a reach change, and a controller change all reproduce byte-identically + /// from the journal, and reopening again reproduces the same state. + #[test] + fn soul_replay_is_exact_across_every_new_arm() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (world_id, expected) = { + let (mut kernel, speech, active) = speech_kernel(directory.path(), "ReplayArms"); + utter( + &mut kernel, + &active, + speech.speaker, + say( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + "The hinge is flooding.", + ), + ) + .expect("the proclamation commits"); + let active = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &active, + operations(vec![ + ComponentOp::AcquireKnowledge { + subject: Ref::Existing(speech.stranger), + fact: Ref::Existing(speech.flood), + source: AuthoredSource::Evidenced, + confidence: Confidence::Certain, + }, + ComponentOp::Communicate { + speaker: Ref::Existing(speech.speaker), + fact: Ref::Existing(speech.flood), + to: AudienceRef::Colocated, + }, + ComponentOp::SetController { + channel: Ref::Existing(speech.horn), + controller: Some(Ref::Existing(speech.listener)), + }, + ComponentOp::SetReach { + channel: Ref::Existing(speech.horn), + reach: ReachRef::Place(Ref::Existing(speech.yard)), + }, + ]), + ); + let active = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Forget { + subject: Ref::Existing(speech.stranger), + fact: Ref::Existing(speech.flood), + }]), + ); + assert!(!kernel.state.knowledge.is_empty()); + assert!(!kernel.state.facts.is_empty()); + (kernel.state.world_id, kernel.state.clone()) + }; + + for _ in 0..2 { + let replayed = WorldKernel::open(&path, world_id).expect("the store replays"); + assert_eq!(replayed.state.facts, expected.facts); + assert_eq!(replayed.state.channels, expected.channels); + assert_eq!(replayed.state.knowledge, expected.knowledge); + assert_eq!(replayed.state.entities, expected.entities); + assert_eq!(replayed.state.events, expected.events); + assert_eq!(replayed.state, expected); + } + } + + /// The statement's bytes are stored twice, and only one of the two copies + /// is a read surface. `facts[fact].statement` is the readable home: + /// `spoken()` and every projection consult it. The committed event's own + /// `AssertClaim` effect carries the same bytes as the replay witness — + /// required so `apply_effect` can re-derive the identical event on replay + /// without re-deriving the statement from elsewhere — but nothing reads + /// that copy back out. Those two are the whole of it, and neither reaches + /// a subject-facing surface. + #[test] + fn soul_the_utterance_is_stored_in_facts_and_in_the_committed_effect() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "OneHome"); + let speak = affordance_named(&active, "speak"); + let text = "A statement that appears nowhere else."; + utter( + &mut kernel, + &active, + speech.speaker, + say(speak, Vec::new(), text), + ) + .expect("the kernel speak commits"); + let claim = minted_claim(&kernel); + + assert_eq!(kernel.state.facts[&claim].statement.as_str(), text); + assert_eq!( + kernel.state.entities[&claim].label, CLAIM_LABEL, + "the label is a name, not a transcript" + ); + // The event no longer embeds the invocation, and its `speech` field is + // the fact id. The bytes still appear in the event, inside the committed + // `AssertClaim` effect. + let event = kernel.state.events.last().unwrap(); + assert_eq!(event.speech, Some(claim)); + assert_eq!( + event.effects[0], + ResolvedOp::AssertClaim { + fact: claim, + statement: Statement::new(text).unwrap(), + by: speech.speaker, + }, + "the event carries the statement as a replay witness, not a second read surface" + ); + // Those two are the whole of it: strip `facts` and `events` and the + // rest of the state is silent. + let mut stripped = kernel.state.clone(); + stripped.facts.clear(); + stripped.events.clear(); + let encoded = rmp_serde::to_vec_named(&stripped).unwrap(); + assert!( + !encoded + .windows(text.len()) + .any(|window| window == text.as_bytes()) + ); + // The statement declared in Draft is untouched by any of it. + assert_eq!( + kernel.state.facts[&speech.flood].statement.as_str(), + FLOOD_STATEMENT + ); + } + + /// `operator_log` is unscoped by construction: it renders every committed + /// act's utterance regardless of who holds knowledge of it. That is correct + /// for the human operator's story feed and is exactly why it must never + /// become reachable from a controller lane. `ControllerRunner` no longer + /// owns a `WorldMailbox`; it owns a `ControllerPort`, which forwards + /// exactly the five requests a controller lane makes and has no + /// `operator_log` method at all. The separation is a type boundary now: + /// `WorldMailbox::operator_log` stays `pub(crate)` for the operator/story + /// feed owner, but nothing inside `controllers.rs` can name it. + #[test] + fn soul_the_operator_log_is_unscoped_and_must_stay_owner_only() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "OperatorLog"); + let text = "Nobody in this room but me."; + utter( + &mut kernel, + &active, + speech.bystander, + say(affordance_named(&active, "speak"), Vec::new(), text), + ) + .expect("speaking alone in the yard commits"); + + // Nobody holds it. + assert!(kernel.state.knowledge.is_empty()); + // The operator reads it anyway, with the speaker resolved by label. + let log = kernel.operator_log().unwrap(); + assert_eq!( + log, + vec![OperatorEvent { + revision: kernel.state.revision, + speaker: speech.bystander, + speaker_label: "The Yard Bystander".into(), + speech: Some(Statement::new(text).unwrap()), + display: None, + verb: "speak".into(), + render_path: None, + roles: Vec::new(), + }] + ); + // And no subject snapshot carries it. + for subject in kernel.snapshot().unwrap().subjects { + assert!(subject.knowledge.is_empty()); + } + } +} + +/// One witnessed event over a place subtree: who it reaches, who it leaves +/// alone, where it is refused, and what it costs an in-flight binding. +#[cfg(test)] +mod witness_tests { + use super::patch::Site; + use super::tests::{ + activate, auth_principal, command, creation, operations, opportunity_for, owner, + reject_owner, submit_owner, + }; + use super::*; + + /// Nesting, because "under a place" is the whole question. A hemisphere + /// holds a region and a far coast; the region holds a village and one + /// unwalked hollow; subjects stand in the village, on the coast, and in the + /// hemisphere under neither. The hollow is empty so an elaborator has a + /// boundary to answer and a witness has a place that reaches nobody. + struct Nesting { + hemisphere: EntityId, + region: EntityId, + village: EntityId, + coast: EntityId, + hollow: EntityId, + villager: SubjectId, + neighbour: SubjectId, + coaster: SubjectId, + drifter: SubjectId, + asteroid: EntityId, + moon: EntityId, + ferry: EdgeId, + } + + fn place(handle: &str, label: &str, container: Option<&str>) -> Declaration { + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: EntityKind::Place, + container: container.map(|value| Ref::Draft(DraftHandle::new(value))), + }) + } + + fn stander(handle: &str, label: &str, place: &str, speak: &Ref) -> Declaration { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + affordances: BTreeSet::from([speak.clone(), Ref::Draft(DraftHandle::new("beacon"))]), + position: Some(Ref::Draft(DraftHandle::new(place))), + import_key: None, + }) + } + + fn sky_fact(handle: &str, label: &str, statement: &str, evidence: &str) -> Declaration { + Declaration::Fact(FactDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + statement: Statement::new(statement).unwrap(), + standing: FactStandingRef::Canonical { + evidence: EvidenceRef::new(evidence), + }, + }) + } + + fn witness(fact: EntityId, place: EntityId, confidence: Confidence) -> ComponentOp { + ComponentOp::Witness { + fact: Ref::Existing(fact), + place: Ref::Existing(place), + confidence, + } + } + + fn nesting_kernel(path: &Path, title: &str) -> (WorldKernel, Nesting, WorldSnapshot) { + let mut kernel = WorldKernel::create( + path.join("world.cc"), + creation(CommandId::new(), title), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let before = kernel.snapshot().unwrap(); + let speak = super::tests::speak_entry(&kernel); + submit_owner( + &mut kernel, + &before, + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![ + place("hemisphere", "The Lit Hemisphere", None), + place("region", "The Rhythm Region", Some("hemisphere")), + place("village", "The Anchor Village", Some("region")), + place("hollow", "The Unwalked Hollow", Some("region")), + place("coast", "The Far Coast", Some("hemisphere")), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("ferry"), + label: "The Coast Ferry".into(), + from: Ref::Draft(DraftHandle::new("coast")), + to: Ref::Draft(DraftHandle::new("village")), + access: AccessKind::Public, + cost: Cost(1), + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("path"), + label: "The Hollow Path".into(), + from: Ref::Draft(DraftHandle::new("village")), + to: Ref::Draft(DraftHandle::new("hollow")), + access: AccessKind::Public, + cost: Cost(1), + }), + // A world-authored verb with no speaker in it: the + // proposer chooses which declared place the entry + // binds and nothing else. + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("beacon"), + kind: AffordanceKindName("beacon".into()), + roles: vec![ + RoleSpec { + role: Role("fact".into()), + kind: RefKind::Entity(EntityKind::Fact), + }, + RoleSpec { + role: Role("place".into()), + kind: RefKind::Entity(EntityKind::Place), + }, + ], + preconditions: Vec::new(), + effect_slots: vec![EffectSlot { + op_kind: ComponentOpKind::Witness { + confidence: Confidence::Believed, + }, + roles: vec![Role("fact".into()), Role("place".into())], + bounds: Bounds::None, + }], + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: vec![0], + }], + carries_speech: false, + }), + stander("villager", "The Anchor Villager", "village", &speak), + stander("neighbour", "The Anchor Neighbour", "village", &speak), + stander("coaster", "The Coast Watcher", "coast", &speak), + stander("drifter", "The Open Drifter", "hemisphere", &speak), + sky_fact( + "asteroid", + "the asteroid over the region", + "An asteroid crossed the sky above the region.", + "vault:asteroid", + ), + sky_fact( + "moon", + "the second moon", + "A second moon rose over the hemisphere.", + "vault:moon", + ), + ], + operations: Vec::new(), + evidence: vec![ + EvidenceRef::new("vault:asteroid"), + EvidenceRef::new("vault:moon"), + ], + }, + }, + ); + let entity = |label: &str| { + *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == label) + .expect("a declared entity") + .0 + }; + let subject = |label: &str| { + *kernel + .state + .subjects + .iter() + .find(|(_, record)| record.label == label) + .expect("a declared subject") + .0 + }; + let nesting = Nesting { + hemisphere: entity("The Lit Hemisphere"), + region: entity("The Rhythm Region"), + village: entity("The Anchor Village"), + coast: entity("The Far Coast"), + hollow: entity("The Unwalked Hollow"), + villager: subject("The Anchor Villager"), + neighbour: subject("The Anchor Neighbour"), + coaster: subject("The Coast Watcher"), + drifter: subject("The Open Drifter"), + asteroid: entity("the asteroid over the region"), + moon: entity("the second moon"), + ferry: *kernel + .state + .edges + .iter() + .find(|(_, record)| record.label() == "The Coast Ferry") + .expect("a declared route") + .0, + }; + let active = activate(&mut kernel); + (kernel, nesting, active) + } + + fn knows(kernel: &WorldKernel, subject: SubjectId, fact: EntityId) -> Option { + kernel + .state + .knowledge + .get(&subject) + .and_then(|held| held.get(&fact)) + .copied() + } + + fn seen(confidence: Confidence, acquired_at: u64) -> Option { + Some(Knowledge { + confidence, + source: KnowledgeSource::Witnessed, + acquired_at, + }) + } + + /// The subtree is the whole reach: everyone under the named place, nobody + /// beside it, and a wider place reaches the wider set. + #[test] + fn a_witness_reaches_every_subject_under_the_place_and_no_other() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, world, active) = nesting_kernel(directory.path(), "Reach"); + submit_owner( + &mut kernel, + &active, + operations(vec![witness( + world.asteroid, + world.region, + Confidence::Believed, + )]), + ); + assert_eq!( + knows(&kernel, world.villager, world.asteroid), + seen(Confidence::Believed, active.revision + 1) + ); + assert_eq!( + knows(&kernel, world.neighbour, world.asteroid), + seen(Confidence::Believed, active.revision + 1) + ); + assert_eq!(knows(&kernel, world.coaster, world.asteroid), None); + assert_eq!(knows(&kernel, world.drifter, world.asteroid), None); + + let after = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &after, + operations(vec![witness( + world.moon, + world.hemisphere, + Confidence::Certain, + )]), + ); + for subject in [ + world.villager, + world.neighbour, + world.coaster, + world.drifter, + ] { + assert_eq!( + knows(&kernel, subject, world.moon), + seen(Confidence::Certain, after.revision + 1) + ); + } + + // No witness names a teller, so nothing in the world was told. + assert!( + kernel + .state + .knowledge + .values() + .flat_map(|held| held.values()) + .all(|entry| !matches!(entry.source, KnowledgeSource::Told { .. })), + "a witness wrote a told row" + ); + } + + /// The knower owns its credence. A holder is dropped from the landing + /// whatever it holds and however it came by it, so a witness cannot reset a + /// mind by repeating itself. + #[test] + fn a_witness_never_overwrites_a_holder() { + let directory = tempfile::tempdir().unwrap(); + let (kernel, world, _) = nesting_kernel(directory.path(), "Holder"); + // `Told` has exactly one writer, so the holder's row is planted at the + // layer that can hold one and the witness is applied beside it. + let held = Knowledge { + confidence: Confidence::Doubted, + source: KnowledgeSource::Told { + by: world.coaster, + via: None, + }, + acquired_at: 0, + }; + let mut state = kernel.state.clone(); + let state_revision = state.revision; + state + .knowledge + .entry(world.villager) + .or_default() + .insert(world.asteroid, held); + apply_operation( + &mut state, + &ResolvedOp::Witness { + fact: world.asteroid, + place: world.region, + confidence: Confidence::Certain, + }, + &[], + state_revision + 1, + ) + .expect("the witness lands"); + assert_eq!(state.knowledge[&world.villager][&world.asteroid], held); + assert_eq!( + state.knowledge[&world.neighbour][&world.asteroid], + Knowledge { + confidence: Confidence::Certain, + source: KnowledgeSource::Witnessed, + acquired_at: state_revision + 1, + } + ); + } + + /// A witnessed event is only its reception, so a landing that reaches + /// nobody is not an event the world recorded. Both layers refuse it, and + /// they refuse the same two cases: an empty subtree, and a subtree whose + /// every stander already holds the fact. + #[test] + fn a_witness_over_nobody_is_refused_at_resolve_and_at_apply() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, world, active) = nesting_kernel(directory.path(), "Nobody"); + let forged = |place: EntityId, state: &WorldState| { + let resolves_to = state.revision + 1; + let mut state = state.clone(); + apply_operation( + &mut state, + &ResolvedOp::Witness { + fact: world.asteroid, + place, + confidence: Confidence::Certain, + }, + &[], + resolves_to, + ) + .unwrap_err() + }; + + assert_eq!( + reject_owner( + &mut kernel, + &active, + operations(vec![witness( + world.asteroid, + world.hollow, + Confidence::Certain + )]), + ), + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + assert!(matches!( + forged(world.hollow, &kernel.state), + KernelError::Invariant(message) + if message == "a witness reaches nobody who does not already hold the fact" + )); + + // Every stander already holds it, which is the same refusal. + submit_owner( + &mut kernel, + &active, + operations(vec![witness( + world.asteroid, + world.village, + Confidence::Certain, + )]), + ); + let after = kernel.snapshot().unwrap(); + assert_eq!( + reject_owner( + &mut kernel, + &after, + operations(vec![witness( + world.asteroid, + world.village, + Confidence::Certain + )]), + ), + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + assert!(matches!( + forged(world.village, &kernel.state), + KernelError::Invariant(message) + if message == "a witness reaches nobody who does not already hold the fact" + )); + + // A forged effect naming a place that is not one, or no live fact, is + // refused by the arm's own kind check before any of that. + let mut state = kernel.state.clone(); + let resolves_to = state.revision + 1; + assert!(matches!( + apply_operation( + &mut state, + &ResolvedOp::Witness { + fact: world.asteroid, + place: world.asteroid, + confidence: Confidence::Certain, + }, + &[], + resolves_to, + ) + .unwrap_err(), + KernelError::Invariant(message) if message == "a witness names no live fact or place" + )); + } + + /// The candidate map models the fan-out, so a subject this patch moved into + /// the subtree is a recipient and a subject it moved out is not. The resolve + /// layer and the apply layer agree on both. + #[test] + fn a_mid_patch_relocation_into_the_subtree_counts() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, world, active) = nesting_kernel(directory.path(), "Relocation"); + // The village's own standers already hold it, so the relocated coaster + // is the only candidate recipient left. + submit_owner( + &mut kernel, + &active, + operations(vec![witness( + world.asteroid, + world.village, + Confidence::Believed, + )]), + ); + let seeded = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &seeded, + operations(vec![ + ComponentOp::Relocate { + subject: Ref::Existing(world.coaster), + via: Ref::Existing(world.ferry), + }, + witness(world.asteroid, world.village, Confidence::Certain), + ]), + ); + assert_eq!( + kernel.state.positions[&world.coaster], + Position { + place: world.village + } + ); + assert_eq!( + knows(&kernel, world.coaster, world.asteroid), + seen(Confidence::Certain, seeded.revision + 1) + ); + + // The inverse: the coast's only stander leaves before the witness, so + // the coast reaches nobody. Both layers say so. + let moved = kernel.snapshot().unwrap(); + assert_eq!( + reject_owner( + &mut kernel, + &moved, + operations(vec![witness(world.moon, world.coast, Confidence::Certain)]), + ), + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + let mut state = kernel.state.clone(); + let resolves_to = state.revision + 1; + assert!(matches!( + apply_operations( + &mut state, + &[ResolvedOp::Witness { + fact: world.moon, + place: world.coast, + confidence: Confidence::Certain, + }], + &[], + resolves_to, + ) + .unwrap_err(), + KernelError::Invariant(message) + if message == "a witness reaches nobody who does not already hold the fact" + )); + } + + /// The place is the whole ground, and it is not a weaker confinement than + /// the recipients: everyone the fan-out selects stands under it. An + /// elaborator witnesses inside its root, and nowhere outside or above it. + #[test] + fn an_elaborator_may_witness_inside_its_root_and_not_outside_or_above() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, world, _) = nesting_kernel(directory.path(), "Jurisdiction"); + let answer = derive_boundaries(&kernel.state) + .unwrap() + .into_iter() + .find(|boundary| { + matches!(boundary, CausalBoundary::UnelaboratedDestination { place, .. } + if *place == world.hollow) + }) + .expect("the hollow is an unelaborated destination"); + let submit = |kernel: &mut WorldKernel, place: EntityId| { + let snapshot = kernel.snapshot().unwrap(); + let caller = CallerId::System(SystemCapability::Elaborator { + jurisdiction: JurisdictionKey::PlaceSubtree(world.region), + }); + kernel.submit( + command( + &snapshot, + CommandId::new(), + caller.clone(), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answer.clone())), + patch: WorldPatch { + // The boundary the elaborator answers: the hollow + // grows a room. The witness rides beside it, and + // only the witness is confined by its place. + declarations: vec![Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("shed"), + label: "The Hollow Shed".into(), + kind: EntityKind::Place, + container: Some(Ref::Existing(world.hollow)), + })], + operations: vec![witness(world.asteroid, place, Confidence::Believed)], + evidence: Vec::new(), + }, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + }; + let outside = |result: Result| match result { + Err(KernelError::PatchRejected(set)) => set, + other => panic!("expected a confined refusal, got {other:?}"), + }; + + assert_eq!( + outside(submit(&mut kernel, world.coast)), + vec![Mismatch::OutsideJurisdiction { + site: Site::Operation(0) + }] + ); + assert_eq!( + outside(submit(&mut kernel, world.hemisphere)), + vec![Mismatch::OutsideJurisdiction { + site: Site::Operation(0) + }] + ); + let before_admit = kernel.state.revision; + let admitted = submit(&mut kernel, world.village); + assert!( + matches!(admitted, Ok(SubmitReceipt::Applied(_))), + "{admitted:?}" + ); + assert_eq!( + knows(&kernel, world.villager, world.asteroid), + seen(Confidence::Believed, before_admit + 1) + ); + } + + /// A consumer names no ground, and a jurisdiction over placeless subjects + /// names no place. Both refuse every witness through the same closure, with + /// no rule in `confine_to_ground` naming the operation. + #[test] + fn a_consumer_cannot_witness() { + let directory = tempfile::tempdir().unwrap(); + let (kernel, world, _) = nesting_kernel(directory.path(), "Consumer"); + let resolved = patch::resolve_patch( + &kernel.state, + CommandId::new(), + &WorldPatch { + declarations: Vec::new(), + operations: vec![witness(world.asteroid, world.village, Confidence::Certain)], + evidence: Vec::new(), + }, + None, + None, + ) + .expect("the witness resolves over committed state"); + for ground in [ + PatchGround::Consumer(ConsumerId::of_name("witness.consumer")), + PatchGround::Jurisdiction(JurisdictionKey::Uncovered), + ] { + assert_eq!( + confine_to_ground(&kernel.state, &resolved, ground), + Err(vec![Mismatch::OutsideJurisdiction { + site: Site::Operation(0) + }]), + "{ground:?} admitted a witness" + ); + } + } + + /// The digest reads the keys of a subject's own knowledge, so a witness + /// moves exactly the digests of the subjects that learned something. + #[test] + fn a_witness_moves_every_recipients_scope_digest_and_nobody_elses() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, world, active) = nesting_kernel(directory.path(), "Digest"); + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::AcquireKnowledge { + subject: Ref::Existing(world.neighbour), + fact: Ref::Existing(world.asteroid), + source: AuthoredSource::Witnessed, + confidence: Confidence::Doubted, + }]), + ); + let digest = |kernel: &WorldKernel, subject_id: SubjectId| { + scope_digest(&kernel.state, DecisionScope { subject_id }).unwrap() + }; + let learner = digest(&kernel, world.villager); + let holder = digest(&kernel, world.neighbour); + let outsider = digest(&kernel, world.coaster); + + let seeded = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &seeded, + operations(vec![witness( + world.asteroid, + world.region, + Confidence::Certain, + )]), + ); + assert_ne!(digest(&kernel, world.villager), learner); + assert_eq!(digest(&kernel, world.neighbour), holder); + assert_eq!(digest(&kernel, world.coaster), outsider); + } + + /// A witness is the loudest producer of a moved scope: every subject that + /// learned something loses its in-flight binding, and every subject that + /// already knew keeps it. What the learner sees carries no speaker. + #[test] + fn a_witness_between_a_bound_opportunity_and_its_exercise_is_a_scope_change() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, world, active) = nesting_kernel(directory.path(), "Interruption"); + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::AcquireKnowledge { + subject: Ref::Existing(world.neighbour), + fact: Ref::Existing(world.asteroid), + source: AuthoredSource::Witnessed, + confidence: Confidence::Doubted, + }]), + ); + let bound = kernel.snapshot().unwrap(); + let learner = opportunity_for(&bound, world.villager); + let holder = opportunity_for(&bound, world.neighbour); + submit_owner( + &mut kernel, + &bound, + operations(vec![witness( + world.asteroid, + world.region, + Confidence::Certain, + )]), + ); + + let exercise = |kernel: &mut WorldKernel, opportunity: &DecisionOpportunity| { + let snapshot = kernel.snapshot().unwrap(); + let speak = *opportunity + .affordance_ids + .iter() + .find(|id| { + snapshot + .affordances + .iter() + .any(|entry| entry.id == **id && entry.entry.carries_speech) + }) + .expect("the scope holds a speech-carrying entry"); + let caller = CallerId::Controller(opportunity.controller_id); + kernel.submit( + command( + &snapshot, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + invocation: DecisionInvocation { + affordance: speak, + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Statement::new("The sky moved.").unwrap()), + display: None, + }, + opportunity: opportunity.clone(), + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + }; + let error = exercise(&mut kernel, &learner).unwrap_err(); + let KernelError::ScopeChanged { + scope, + expected, + actual, + } = error + else { + panic!("expected a changed scope, got {error:?}"); + }; + assert_eq!(scope, learner.scope); + assert_eq!(expected, learner.scope_digest); + assert_ne!(expected, actual); + + // The subject that already held the fact learned nothing, so its + // binding survives the same witness. + let kept = exercise(&mut kernel, &holder); + assert!(matches!(kept, Ok(SubmitReceipt::Applied(_))), "{kept:?}"); + + // What the learner now holds names no speaker: it knows the thing, not + // the telling. + let entry = knows(&kernel, world.villager, world.asteroid).expect("the learner holds it"); + assert_eq!(entry.source, KnowledgeSource::Witnessed); + let snapshot = kernel.snapshot().unwrap(); + let held = snapshot + .subjects + .iter() + .find(|subject| subject.id == world.villager) + .expect("the learner is snapshotted") + .knowledge + .iter() + .find(|row| row.fact == world.asteroid) + .expect("the learner's snapshot carries the fact"); + assert_eq!(held.source, KnowledgeSource::Witnessed); + assert!( + held.minted_at.is_none(), + "a witnessed row named a speech act" + ); + } + + /// The slot names a fact and a place, never a subject, so an exercised + /// witness lands the subtree with no teller anywhere in it. A slot whose + /// place position binds a subject is refused before it is ever declared. + #[test] + fn a_witness_affordance_lowers_with_no_speaker() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, world, active) = nesting_kernel(directory.path(), "Affordance"); + let opportunity = opportunity_for(&active, world.villager); + let beacon = *opportunity + .affordance_ids + .iter() + .find(|id| { + active + .affordances + .iter() + .any(|entry| entry.id == **id && entry.entry.kind.0 == "beacon") + }) + .expect("the villager holds the beacon entry"); + let caller = CallerId::Controller(opportunity.controller_id); + kernel + .submit( + command( + &active, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + invocation: DecisionInvocation { + affordance: beacon, + bindings: vec![ + RoleBinding { + role: Role("fact".into()), + target: Target::Entity(world.asteroid), + }, + RoleBinding { + role: Role("place".into()), + target: Target::Entity(world.region), + }, + ], + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + speech: None, + display: None, + }, + opportunity: opportunity.clone(), + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .expect("the beacon lands"); + assert_eq!( + kernel + .state + .events + .last() + .expect("a committed event") + .effects, + vec![ResolvedOp::Witness { + fact: world.asteroid, + place: world.region, + confidence: Confidence::Believed, + }] + ); + assert_eq!( + knows(&kernel, world.villager, world.asteroid), + seen(Confidence::Believed, active.revision + 1) + ); + assert_eq!( + knows(&kernel, world.neighbour, world.asteroid), + seen(Confidence::Believed, active.revision + 1) + ); + assert_eq!(knows(&kernel, world.coaster, world.asteroid), None); + + // The second role is a place, and a subject cannot serve it, so a slot + // that named one is refused at affordance declaration. + let rules = ComponentOpKind::Witness { + confidence: Confidence::Believed, + } + .arity(); + assert_eq!(rules.len(), 2); + assert!(patch::role_kind_fits( + &rules[0], + RefKind::Entity(EntityKind::Fact) + )); + assert!(patch::role_kind_fits( + &rules[1], + RefKind::Entity(EntityKind::Place) + )); + assert!(!patch::role_kind_fits(&rules[1], RefKind::Subject(None))); + } + + /// A journal carrying a witness replays to digest equality, and the rows it + /// wrote pass the shape check with no clause of their own. + #[test] + fn a_world_with_a_witness_replays() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, world, active) = nesting_kernel(directory.path(), "Replay"); + submit_owner( + &mut kernel, + &active, + operations(vec![witness( + world.asteroid, + world.region, + Confidence::Certain, + )]), + ); + assert!(journal::verify_state_shape(&kernel.state).is_ok()); + let world_id = kernel.state.world_id; + let committed = kernel.state.clone(); + drop(kernel); + let reopened = + WorldKernel::open(directory.path().join("world.cc"), world_id).expect("it replays"); + assert_eq!(reopened.state, committed); + assert_eq!( + knows(&reopened, world.villager, world.asteroid), + seen(Confidence::Certain, active.revision + 1) + ); + } + + /// PA.f49: `acquired_at` stamps the revision the write's own commit + /// resolves to on every path, genesis included. Genesis resolves to + /// revision 0 itself — `state.revision` never advances past 0 for the + /// creating commit — so a fact a genesis patch both declares and grants + /// knowledge of lands at `acquired_at: 0`, not one revision ahead of the + /// state it was written into. + #[test] + fn a_genesis_seeded_knowledge_row_is_acquired_at_revision_zero() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let mut creation = creation(CommandId::new(), "PAf49Genesis"); + creation.patch.declarations.push(Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("founding"), + label: "The Founding Ruling".into(), + statement: Statement::new("Stated by the table.").unwrap(), + standing: FactStandingRef::Claimed { + by: Ref::Draft(DraftHandle::new("human")), + }, + })); + creation.patch.operations.push(ComponentOp::AcquireKnowledge { + subject: Ref::Draft(DraftHandle::new("human")), + fact: Ref::Draft(DraftHandle::new("founding")), + source: AuthoredSource::Witnessed, + confidence: Confidence::Certain, + }); + let (kernel, _) = WorldKernel::create(&path, creation, &auth_principal(owner())).unwrap(); + assert_eq!(kernel.state.revision, 0); + let human = *kernel + .state + .subjects + .iter() + .find(|(_, subject)| subject.label == "The Human") + .expect("genesis admits the declared human") + .0; + let fact = *kernel + .state + .facts + .iter() + .find(|(_, record)| record.statement.as_str() == "Stated by the table.") + .expect("genesis admits the declared fact") + .0; + assert_eq!( + kernel.state.knowledge[&human][&fact].acquired_at, + 0, + "a genesis-seeded row landed one revision ahead of the state it was written into" + ); + assert!(journal::verify_state_shape(&kernel.state).is_ok()); + } + + /// PA.f49: every commit after genesis still stamps the revision it + /// resolves to, one past the state it was applied against. + #[test] + fn a_later_commits_knowledge_row_is_acquired_at_that_commits_revision() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, world, active) = nesting_kernel(directory.path(), "PAf49Later"); + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::AcquireKnowledge { + subject: Ref::Existing(world.villager), + fact: Ref::Existing(world.asteroid), + source: AuthoredSource::Witnessed, + confidence: Confidence::Certain, + }]), + ); + assert_eq!(kernel.state.revision, active.revision + 1); + assert_eq!( + kernel.state.knowledge[&world.villager][&world.asteroid].acquired_at, + active.revision + 1 + ); + } + + /// PA.f49: the shape check refuses a knowledge row forged ahead of the + /// world's own revision — the check `verify_state_shape` gained alongside + /// the genesis fix, so a corrupt or forged `acquired_at` cannot pass + /// replay silently. + #[test] + fn a_shape_check_refuses_a_knowledge_row_forged_ahead_of_the_world_revision() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, world, active) = nesting_kernel(directory.path(), "PAf49Shape"); + submit_owner( + &mut kernel, + &active, + operations(vec![witness( + world.asteroid, + world.region, + Confidence::Certain, + )]), + ); + assert!(journal::verify_state_shape(&kernel.state).is_ok()); + let mut forged = kernel.state.clone(); + let entry = forged + .knowledge + .get_mut(&world.villager) + .and_then(|held| held.get_mut(&world.asteroid)) + .expect("the witness landed on the villager"); + entry.acquired_at = forged.revision + 1; + assert!(journal::verify_state_shape(&forged).is_err()); + } + + /// The two callers of the shared owners answer the same question. A + /// `Reach::Place` channel's fan-out and a witness over the same place select + /// the same subjects over the same state, so "under a place" and "already a + /// knower" cannot drift between a declared broadcast area and a witnessed + /// event. A grep proves there is one body; this proves the two lanes reach + /// it. + #[test] + fn soul_a_place_reach_fan_out_and_a_witness_select_the_same_subjects() { + let directory = tempfile::tempdir().unwrap(); + let (kernel, world, _) = nesting_kernel(directory.path(), "One owner"); + let mut state = kernel.state.clone(); + // One holder, so the already-holds half of the selection is exercised + // and not merely the subtree half. + state.knowledge.entry(world.neighbour).or_default().insert( + world.asteroid, + Knowledge { + confidence: Confidence::Doubted, + source: KnowledgeSource::Witnessed, + acquired_at: 0, + }, + ); + for root in [world.hemisphere, world.region, world.village, world.coast] { + let horn = state + .entities + .keys() + .copied() + .find(|id| !state.channels.contains_key(id)) + .expect("an unused key for the horn"); + state.channels.insert( + horn, + patch::ChannelRecord { + reach: patch::Reach::Place(root), + controller: None, + }, + ); + for speaker in [world.coaster, world.drifter, world.villager] { + // `fan_out` is exactly the shared pair with the speaker taken + // out; the speaker clause is the only thing it owns itself. + let mut expected = under_place(&state, root); + expected.remove(&speaker); + assert_eq!( + fan_out( + &state, + speaker, + world.asteroid, + &patch::Audience::Channel(horn), + ), + unheld(&state, world.asteroid, expected), + "the two lanes disagreed about {root:?} for {speaker:?}" + ); + } + state.channels.remove(&horn); + } + } + + /// Presence in the subtree is read from `positions` alone. A place covers + /// itself, covers its children transitively, and covers nothing beside it; + /// a subject standing nowhere is under nothing, at every root including the + /// world's widest. + #[test] + fn soul_under_place_covers_itself_and_below_and_never_the_placeless() { + let directory = tempfile::tempdir().unwrap(); + let (kernel, world, _) = nesting_kernel(directory.path(), "Nesting"); + let under = |root: EntityId| under_place(&kernel.state, root); + // The village holds its two standers and nobody else. + assert_eq!( + under(world.village), + BTreeSet::from([world.villager, world.neighbour]) + ); + // The region covers the village transitively and the drifter standing + // one level above it is not swept in. + assert_eq!( + under(world.region), + BTreeSet::from([world.villager, world.neighbour]) + ); + // The hemisphere covers everything below it and the drifter standing + // exactly at it, not merely below. + assert_eq!( + under(world.hemisphere), + BTreeSet::from([ + world.villager, + world.neighbour, + world.coaster, + world.drifter, + ]) + ); + assert_eq!(under(world.coast), BTreeSet::from([world.coaster])); + assert!(under(world.hollow).is_empty()); + + // A subject with no position is under nothing, at every root including + // the world's widest, and the widest witness in the world does not + // reach it. Presence is read from `positions` alone: there is no second + // notion of being somewhere for a placeless subject to fall back on. + let mut adrift = kernel.state.clone(); + let adrift_revision = adrift.revision; + adrift.positions.remove(&world.drifter); + for root in [ + world.hemisphere, + world.region, + world.village, + world.coast, + world.hollow, + ] { + assert!( + !under_place(&adrift, root).contains(&world.drifter), + "a placeless subject was under {root:?}" + ); + } + apply_operation( + &mut adrift, + &ResolvedOp::Witness { + fact: world.moon, + place: world.hemisphere, + confidence: Confidence::Certain, + }, + &[], + adrift_revision + 1, + ) + .expect("the hemisphere still reaches the standers"); + assert!( + !adrift + .knowledge + .get(&world.drifter) + .is_some_and(|held| held.contains_key(&world.moon)), + "a placeless subject witnessed the widest event in the world" + ); + for subject in [world.villager, world.neighbour, world.coaster] { + assert_eq!( + adrift.knowledge[&subject][&world.moon], + Knowledge { + confidence: Confidence::Certain, + source: KnowledgeSource::Witnessed, + acquired_at: adrift_revision + 1, + } + ); + } + } + + /// The candidate model and the apply arm are handed a patch built so they + /// could disagree: the only subject the witness can reach is one this same + /// patch declares and places, and every subject already standing there + /// already holds the fact. If the resolver did not see the draft stander it + /// would refuse a landing the apply pass performs; if the apply pass did + /// not see it, it would refuse a landing the resolver admitted. Both see + /// it. The inverse — a draft subject declared with no position — is refused + /// by both. + #[test] + fn soul_a_subject_declared_and_placed_in_one_patch_is_a_recipient_at_both_layers() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, world, active) = nesting_kernel(directory.path(), "Draft stander"); + submit_owner( + &mut kernel, + &active, + operations(vec![witness( + world.asteroid, + world.village, + Confidence::Believed, + )]), + ); + // An active world admits declarations only through the elaborator lane, + // which is also the lane whose confinement the witness must satisfy. + let answer = derive_boundaries(&kernel.state) + .unwrap() + .into_iter() + .find(|boundary| { + matches!(boundary, CausalBoundary::UnelaboratedDestination { place, .. } + if *place == world.hollow) + }) + .expect("the hollow is an unelaborated destination"); + let beacon = *kernel + .state + .affordance_catalog + .iter() + .find(|(_, entry)| entry.kind.0 == "beacon") + .expect("the beacon entry is declared") + .0; + let arrival = + |kernel: &mut WorldKernel, handle: &str, label: &str, position: Option| { + let snapshot = kernel.snapshot().unwrap(); + let caller = CallerId::System(SystemCapability::Elaborator { + jurisdiction: JurisdictionKey::PlaceSubtree(world.region), + }); + kernel.submit( + command( + &snapshot, + CommandId::new(), + caller.clone(), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answer.clone())), + patch: WorldPatch { + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("shed"), + label: format!("The Hollow Shed for {handle}"), + kind: EntityKind::Place, + container: Some(Ref::Existing(world.hollow)), + }), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + // Every non-mirror subject must hold one. + affordances: BTreeSet::from([Ref::Existing(beacon)]), + position: position.map(Ref::Existing), + import_key: None, + }), + ], + operations: vec![witness( + world.asteroid, + world.village, + Confidence::Certain, + )], + evidence: Vec::new(), + }, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + }; + + // Declared with no position: under nothing, so the witness still + // reaches nobody and the resolver says so. + match arrival(&mut kernel, "ghost", "The Unplaced Arrival", None) { + Err(KernelError::PatchRejected(set)) => assert_eq!( + set, + vec![Mismatch::NoOperationEffect { operation: 0 }], + "a placeless draft subject was counted as a recipient" + ), + other => panic!("expected a refusal, got {other:?}"), + } + + // Declared and placed under the witnessed place: the resolver's + // candidate map carries the draft position, and the apply pass derives + // the same subject from live state. + let before_arrival = kernel.state.revision; + let receipt = arrival( + &mut kernel, + "arrival", + "The Village Arrival", + Some(world.village), + ); + assert!( + matches!(receipt, Ok(SubmitReceipt::Applied(_))), + "{receipt:?}" + ); + let arrived = *kernel + .state + .subjects + .iter() + .find(|(_, record)| record.label == "The Village Arrival") + .expect("the arrival is declared") + .0; + assert_eq!( + knows(&kernel, arrived, world.asteroid), + seen(Confidence::Certain, before_arrival + 1) + ); + // The standers who already held it kept their own rows, from the + // earlier witness, and this landing did not touch them. + assert_eq!( + knows(&kernel, world.villager, world.asteroid), + seen(Confidence::Believed, active.revision + 1) + ); + assert_eq!( + knows(&kernel, world.neighbour, world.asteroid), + seen(Confidence::Believed, active.revision + 1) + ); + } + + /// The other way the two layers could disagree about who already holds the + /// fact: an earlier operation in the same patch takes it away. The + /// resolver's candidate map drops the row and the apply pass drops the + /// stored one, so a forget-then-witness lands rather than being refused as + /// reaching nobody. + #[test] + fn soul_a_forget_before_a_witness_agrees_at_both_layers() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, world, active) = nesting_kernel(directory.path(), "Forget first"); + submit_owner( + &mut kernel, + &active, + operations(vec![witness( + world.asteroid, + world.village, + Confidence::Believed, + )]), + ); + // Everyone under the village holds it, so the witness alone is refused. + let seeded = kernel.snapshot().unwrap(); + assert_eq!( + reject_owner( + &mut kernel, + &seeded, + operations(vec![witness( + world.asteroid, + world.village, + Confidence::Certain + )]), + ), + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + + let seeded = kernel.snapshot().unwrap(); + let receipt = submit_owner( + &mut kernel, + &seeded, + operations(vec![ + ComponentOp::Forget { + subject: Ref::Existing(world.villager), + fact: Ref::Existing(world.asteroid), + }, + witness(world.asteroid, world.village, Confidence::Certain), + ]), + ); + assert!(matches!(receipt, SubmitReceipt::Applied(_)), "{receipt:?}"); + assert_eq!( + knows(&kernel, world.villager, world.asteroid), + seen(Confidence::Certain, seeded.revision + 1), + "the forgotten subject was not re-reached" + ); + assert_eq!( + knows(&kernel, world.neighbour, world.asteroid), + seen(Confidence::Believed, active.revision + 1), + "a holder the patch did not touch was overwritten" + ); + } + + /// The brief is the world's authored premise: trimmed at ingress, carried + /// on the state and its snapshot, and identical after replay. + #[test] + fn the_world_brief_is_authored_once_trimmed_and_replayed() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let mut creation = creation(CommandId::new(), "Low Sere"); + creation.brief = " A dry basin town that owes its water to the gate above it. ".into(); + let (kernel, _) = WorldKernel::create(&path, creation, &auth_principal(owner())).unwrap(); + let created = kernel.snapshot().unwrap(); + assert_eq!( + created.brief, + "A dry basin town that owes its water to the gate above it." + ); + drop(kernel); + let reopened = WorldKernel::open(&path, created.world_id).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), created); + } + + /// Persona material is set whole, refused when any text is non-canonical + /// or a read names a subject twice, refused when identical to what the + /// subject holds, and outside the scope digest: setting it moves no + /// opportunity's binding. + #[test] + fn soul_persona_material_is_set_whole_and_outside_the_scope_digest() { + use crate::patch::PersonaReadRef; + + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, world, active) = nesting_kernel(directory.path(), "Material"); + let text = |value: &str| Statement::new(value).unwrap(); + let material = |voice: Statement, reads: Vec| ComponentOp::SetPersonaMaterial { + subject: Ref::Existing(world.villager), + values: vec![text("Water is owed upward.")], + voice, + memories: vec![text("The gate froze the winter the ferry sank.")], + reads, + }; + let read = |subject: SubjectId| PersonaReadRef { + subject: Ref::Existing(subject), + statement: text("Counts every jar twice."), + }; + let digest_of = |snapshot: &WorldSnapshot| { + snapshot + .opportunities + .iter() + .find(|opportunity| opportunity.scope.subject_id == world.villager) + .map(|opportunity| opportunity.scope_digest.clone()) + }; + let before = digest_of(&active); + + // Padded text is refused at resolve, as is a subject read twice. + let padded: Statement = serde_json::from_value(serde_json::json!(" padded ")).unwrap(); + assert_eq!( + reject_owner( + &mut kernel, + &active, + operations(vec![material(padded, vec![read(world.neighbour)])]), + ), + vec![Mismatch::NoncanonicalText { operation: 0 }] + ); + assert_eq!( + reject_owner( + &mut kernel, + &active, + operations(vec![material( + text("Dry and exact."), + vec![read(world.neighbour), read(world.neighbour)], + )]), + ), + vec![Mismatch::NoncanonicalText { operation: 0 }] + ); + // A read of a subject the world does not hold is refused. + assert!( + !reject_owner( + &mut kernel, + &active, + operations(vec![material( + text("Dry and exact."), + vec![read(SubjectId::issue())], + )]), + ) + .is_empty() + ); + + let receipt = submit_owner( + &mut kernel, + &active, + operations(vec![material(text("Dry and exact."), vec![read(world.neighbour)])]), + ); + assert!(matches!(receipt, SubmitReceipt::Applied(_)), "{receipt:?}"); + let held = kernel.snapshot().unwrap(); + let villager = held + .subjects + .iter() + .find(|subject| subject.id == world.villager) + .unwrap(); + let carried = villager.material.as_ref().expect("material was set"); + assert_eq!(carried.voice.as_str(), "Dry and exact."); + assert_eq!( + carried.reads.get(&world.neighbour).map(Statement::as_str), + Some("Counts every jar twice.") + ); + assert_eq!(digest_of(&held), before, "material moved a scope digest"); + + // Identical material changes nothing; different material replaces all. + assert_eq!( + reject_owner( + &mut kernel, + &held, + operations(vec![material(text("Dry and exact."), vec![read(world.neighbour)])]), + ), + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + let held = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &held, + operations(vec![material(text("Slow and courteous."), Vec::new())]), + ); + let replaced = kernel.snapshot().unwrap(); + let carried = replaced + .subjects + .iter() + .find(|subject| subject.id == world.villager) + .unwrap() + .material + .clone() + .unwrap(); + assert_eq!(carried.voice.as_str(), "Slow and courteous."); + assert!(carried.reads.is_empty(), "a whole-value set kept an old read"); + } + + /// What a witness hands the narrative lane's interruption renderer. The + /// renderer takes a subject's own `ScopeComponents` and its own knowledge + /// rows and nothing else, so both of its inputs are pinned here rather than + /// in the lane that owns the prose: exactly one component moved, `knows`, + /// which is the anonymous line and names no author; and the row the witness + /// wrote carries no `minted_at`, which is the sole gate on an `Overheard` + /// row, so no attributable line can be built from it. + #[test] + fn soul_a_witness_moves_only_knows_and_writes_no_spoken_row() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, world, active) = nesting_kernel(directory.path(), "Anonymous"); + let before = scope_components(&kernel.state, world.villager); + submit_owner( + &mut kernel, + &active, + operations(vec![witness( + world.asteroid, + world.region, + Confidence::Certain, + )]), + ); + let after = scope_components(&kernel.state, world.villager); + assert_ne!(before.knows, after.knows); + assert_eq!( + after, + ScopeComponents { + knows: after.knows.clone(), + ..before + }, + "a witness moved a component other than what this person knows" + ); + + let snapshot = kernel.snapshot().unwrap(); + let held = snapshot + .subjects + .iter() + .find(|subject| subject.id == world.villager) + .expect("the learner is snapshotted"); + assert!( + held.knowledge + .iter() + .filter(|row| row.fact == world.asteroid) + .all(|row| row.minted_at.is_none() && row.source == KnowledgeSource::Witnessed), + "a witnessed row carried a speech act" + ); + } +} + +/// The clock, commitments, pressure, ordered attention, boundaries, and scale. +#[cfg(test)] +mod clock_tests { + use super::patch::{PreconditionRef, PressureSourceRef, WorldScaleIntentRef}; + use super::tests::{ + activate, affordance_named, authority_kind, auth_principal, command, creation, office, + operations, opportunity_for, owner, human_principal, reject_owner, speech_world, + submit_owner, + }; + use super::*; + use std::path::Path; + + /// The canonical IDs of the clock fixture: a hall containing a yard, a + /// dead end reached by exactly one route, three subjects, a resource, and + /// one commitment of each kind. + pub(crate) struct Clockwork { + yard: EntityId, + dead_end: EntityId, + gate: EdgeId, + reeve: SubjectId, + farmer: SubjectId, + treasury: SubjectId, + routine: CommitmentKey, + obligation: CommitmentKey, + goal: CommitmentKey, + deliver: AffordanceId, + threaten: AffordanceId, + } + + const ROUTINE_DUE: u64 = 60; + const LATE_DUE: u64 = 100; + + fn minutes(value: u32) -> TickMinutes { + TickMinutes::new(value).expect("a valid span") + } + + fn clock_kernel(path: &Path, title: &str) -> (WorldKernel, Clockwork, WorldSnapshot) { + let mut kernel = WorldKernel::create( + path.join("world.cc"), + creation(CommandId::new(), title), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let (clockwork, active) = clock_world(&mut kernel); + (kernel, clockwork, active) + } + + fn clock_world(kernel: &mut WorldKernel) -> (Clockwork, WorldSnapshot) { + let before = kernel.snapshot().unwrap(); + let speak = super::tests::speak_entry(kernel); + let person = |handle: &str, label: &str, kind: SubjectKind, place: &str| { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind, + controller: NewController::NarrativePersona, + affordances: BTreeSet::from([ + speak.clone(), + Ref::Draft(DraftHandle::new("deliver")), + Ref::Draft(DraftHandle::new("threaten")), + ]), + position: Some(Ref::Draft(DraftHandle::new(place))), + import_key: None, + }) + }; + let subject = |handle: &str| Ref::Draft(DraftHandle::new(handle)); + submit_owner( + kernel, + &before, + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + evidence: vec![EvidenceRef::new("vault:harvest")], + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("hall"), + label: "The Long Hall".into(), + kind: EntityKind::Place, + container: None, + }), + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("yard"), + label: "The Cavity Yard".into(), + kind: EntityKind::Place, + container: Some(Ref::Draft(DraftHandle::new("hall"))), + }), + // Nothing inside it, nobody in it, and one route out: + // the world has not grown into it yet. + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("dead-end"), + label: "The Unwalked Road".into(), + kind: EntityKind::Place, + container: None, + }), + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("grain"), + label: "Winter Grain".into(), + kind: EntityKind::Resource, + container: None, + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("stair"), + label: "The Yard Stair".into(), + from: Ref::Draft(DraftHandle::new("yard")), + to: Ref::Draft(DraftHandle::new("hall")), + access: AccessKind::Public, + cost: Cost(1), + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("back"), + label: "The Hall Steps".into(), + from: Ref::Draft(DraftHandle::new("hall")), + to: Ref::Draft(DraftHandle::new("yard")), + access: AccessKind::Public, + cost: Cost(1), + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("gate"), + label: "The Field Gate".into(), + from: Ref::Draft(DraftHandle::new("hall")), + to: Ref::Draft(DraftHandle::new("dead-end")), + access: AccessKind::Public, + cost: Cost(1), + }), + // An affordance whose legitimacy is a promise rather + // than a jurisdiction, and one that presses directly. + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("deliver"), + kind: AffordanceKindName("deliver".into()), + roles: vec![RoleSpec { + role: Role("creditor".into()), + kind: RefKind::Subject(None), + }], + preconditions: vec![Precondition::Committed { + to: Role("creditor".into()), + kind: CommitmentKind::Obligation, + }], + effect_slots: vec![EffectSlot { + op_kind: ComponentOpKind::CreateCommitment { + kind: CommitmentKind::Obligation, + horizon: minutes(1440), + period: None, + }, + roles: vec![Role("actor".into()), Role("creditor".into())], + bounds: Bounds::None, + }], + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: vec![0], + }], + carries_speech: false, + }), + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("threaten"), + kind: AffordanceKindName("threaten".into()), + roles: vec![RoleSpec { + role: Role("target".into()), + kind: RefKind::Subject(None), + }], + preconditions: Vec::new(), + effect_slots: vec![EffectSlot { + op_kind: ComponentOpKind::AdvancePressure { + by: PressureMagnitude(3), + }, + roles: vec![Role("target".into())], + bounds: Bounds::None, + }], + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: vec![0], + }], + carries_speech: false, + }), + person("reeve", "The Yard Reeve", SubjectKind::Person, "yard"), + person("farmer", "The Yard Farmer", SubjectKind::Person, "yard"), + person( + "treasury", + "The Hall Treasury", + SubjectKind::Institution, + "hall", + ), + ], + operations: vec![ + ComponentOp::Admit { + holder: subject("farmer"), + resource: Ref::Draft(DraftHandle::new("grain")), + qty: Quantity(4), + evidence: EvidenceRef::new("vault:harvest"), + }, + // 0: the routine, whose check is where its subject stands. + ComponentOp::CreateCommitment { + subject: subject("farmer"), + counterparty: None, + kind: CommitmentKind::Routine, + due: FictionalMinutes(ROUTINE_DUE), + period: Some(minutes(10)), + checks: vec![PreconditionRef::Present { + at: Ref::Draft(DraftHandle::new("yard")), + }], + statement: Statement::new("What was promised, as the promisor would say it.").unwrap(), + }, + ComponentOp::CreateCommitment { + subject: subject("farmer"), + counterparty: Some(subject("treasury")), + kind: CommitmentKind::Obligation, + due: FictionalMinutes(LATE_DUE), + period: None, + checks: Vec::new(), + statement: Statement::new("What was promised, as the promisor would say it.").unwrap(), + }, + ComponentOp::CreateCommitment { + subject: subject("reeve"), + counterparty: None, + kind: CommitmentKind::Goal, + due: FictionalMinutes(LATE_DUE), + period: None, + checks: Vec::new(), + statement: Statement::new("What was promised, as the promisor would say it.").unwrap(), + }, + ComponentOp::Bind { + subject: subject("reeve"), + target: DependencyRef::Route(Ref::Draft(DraftHandle::new("gate"))), + }, + ], + }, + }, + ); + let active = activate(kernel); + let place = |label: &str| { + active + .places + .iter() + .find(|place| place.label == label) + .expect("the declared place") + .id + }; + let who = |label: &str| { + active + .subjects + .iter() + .find(|subject| subject.label == label) + .expect("the declared subject") + .id + }; + let reeve = who("The Yard Reeve"); + let farmer = who("The Yard Farmer"); + let key_of = |subject: SubjectId, kind: CommitmentKind| { + *kernel + .state + .commitments + .get(&subject) + .expect("the subject holds commitments") + .iter() + .find(|(_, commitment)| commitment.kind == kind) + .expect("the declared commitment") + .0 + }; + let gate = active + .routes + .iter() + .find(|route| route.label == "The Field Gate") + .expect("the declared route") + .id; + ( + Clockwork { + yard: place("The Cavity Yard"), + dead_end: place("The Unwalked Road"), + gate, + reeve, + farmer, + treasury: who("The Hall Treasury"), + routine: key_of(farmer, CommitmentKind::Routine), + obligation: key_of(farmer, CommitmentKind::Obligation), + goal: key_of(reeve, CommitmentKind::Goal), + deliver: affordance_named(&active, "deliver"), + threaten: affordance_named(&active, "threaten"), + }, + active, + ) + } + + fn clock_caller() -> CallerId { + CallerId::System(SystemCapability::Clock) + } + + fn tick(kernel: &mut WorldKernel, span: u32) -> Result { + let snapshot = kernel.snapshot().unwrap(); + kernel.submit( + command( + &snapshot, + CommandId::new(), + clock_caller(), + CommandBody::AdvanceTime { + minutes: minutes(span), + }, + ), + &AuthenticatedCaller::fixture(clock_caller()), + ) + } + + fn exercise( + kernel: &mut WorldKernel, + actor: SubjectId, + affordance: AffordanceId, + bindings: Vec, + ) -> Result { + let snapshot = kernel.snapshot().unwrap(); + let opportunity = opportunity_for(&snapshot, actor); + let caller = CallerId::Controller(opportunity.controller_id); + kernel.submit( + command( + &snapshot, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + opportunity, + invocation: DecisionInvocation { + affordance, + bindings, + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + speech: None, + display: None, + }, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + } + + fn binding(role: &str, target: Target) -> RoleBinding { + RoleBinding { + role: Role(role.into()), + target, + } + } + + fn pressure(kernel: &WorldKernel, target: SubjectId, source: PressureSource) -> u32 { + kernel + .state + .pressures + .get(&target) + .and_then(|held| held.get(&source)) + .map_or(0, |magnitude| magnitude.0) + } + + fn due(kernel: &WorldKernel, subject: SubjectId, key: CommitmentKey) -> FictionalMinutes { + kernel + .state + .commitments + .get(&subject) + .and_then(|held| held.get(&key)) + .expect("the live commitment") + .due + } + + /// Verification 12, both halves: a defaulted commitment advances pressure on + /// its subject, and that subject still derives exactly one opportunity. + #[test] + fn a_defaulted_commitment_advances_pressure_and_the_subject_derives_an_opportunity() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Default"); + let sourced = PressureSource::Commitment { + subject: clockwork.farmer, + key: clockwork.obligation, + }; + + tick(&mut kernel, 120).expect("the tick commits"); + assert_eq!(pressure(&kernel, clockwork.farmer, sourced), 1); + assert_eq!( + kernel.state.pressures[&clockwork.farmer].len(), + 1, + "only the past-due obligation pressed the farmer" + ); + let snapshot = kernel.snapshot().unwrap(); + assert_eq!( + snapshot + .opportunities + .iter() + .filter(|opportunity| opportunity.scope.subject_id == clockwork.farmer) + .count(), + 1 + ); + + tick(&mut kernel, 1).expect("the second tick commits"); + assert_eq!(pressure(&kernel, clockwork.farmer, sourced), 2); + } + + /// Verification 19: a due routine fulfils with no inference and no pressure, + /// and a blocked one neither rolls nor presses. + #[test] + fn a_due_routine_auto_fulfils_and_a_blocked_one_does_not() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, active) = clock_kernel(directory.path(), "Routine"); + let holdings = kernel.state.holdings.clone(); + let positions = kernel.state.positions.clone(); + let edges = kernel.state.edges.clone(); + + tick(&mut kernel, ROUTINE_DUE as u32).expect("the tick commits"); + assert_eq!( + due(&kernel, clockwork.farmer, clockwork.routine), + FictionalMinutes(ROUTINE_DUE + 10) + ); + assert!( + kernel.state.pressures.is_empty(), + "a routine raises nothing" + ); + assert_eq!(kernel.state.holdings, holdings); + assert_eq!(kernel.state.positions, positions); + assert_eq!(kernel.state.edges, edges); + + // Out of the yard: the check fails, so the routine neither rolls nor + // presses, and it retries on the next tick. + let route = |label: &str| { + active + .routes + .iter() + .find(|route| route.label == label) + .expect("the declared route") + .id + }; + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::Relocate { + subject: Ref::Existing(clockwork.farmer), + via: Ref::Existing(route("The Yard Stair")), + }]), + ); + tick(&mut kernel, 10).expect("the tick commits"); + assert_eq!( + due(&kernel, clockwork.farmer, clockwork.routine), + FictionalMinutes(ROUTINE_DUE + 10) + ); + assert!( + kernel.state.pressures.is_empty(), + "a blocked routine neither rolls nor presses" + ); + + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::Relocate { + subject: Ref::Existing(clockwork.farmer), + via: Ref::Existing(route("The Hall Steps")), + }]), + ); + tick(&mut kernel, 1).expect("the tick commits"); + assert_eq!( + due(&kernel, clockwork.farmer, clockwork.routine), + FictionalMinutes(ROUTINE_DUE + 20) + ); + } + + /// A tick with nothing due is still a commit: the clock moved, which is a + /// canonical change. + #[test] + fn a_tick_with_nothing_due_moves_only_the_clock() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, _, _) = clock_kernel(directory.path(), "Quiet"); + let before = kernel.state.clone(); + + tick(&mut kernel, 1).expect("the tick commits"); + assert_eq!(kernel.state.now, FictionalMinutes(1)); + assert_eq!(kernel.state.revision, before.revision + 1); + assert!(kernel.state.pressures.is_empty()); + assert_eq!(kernel.state.commitments, before.commitments); + assert_eq!(kernel.state.holdings, before.holdings); + assert_eq!(kernel.state.positions, before.positions); + assert_eq!(kernel.state.events, before.events); + + tick(&mut kernel, 2).expect("the tick commits"); + assert_eq!(kernel.state.now, FictionalMinutes(3)); + } + + /// A closed route in one place becomes political pressure in another without + /// anyone deciding that it should. The tick never reduces; only an operation + /// does. + #[test] + fn an_unavailable_dependency_presses_its_depender() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Dependency"); + let sourced = PressureSource::Dependency(DependencyTarget::Route(clockwork.gate)); + + tick(&mut kernel, 1).expect("the tick commits"); + assert_eq!(pressure(&kernel, clockwork.reeve, sourced), 0); + + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::CloseRoute { + route: Ref::Existing(clockwork.gate), + }]), + ); + tick(&mut kernel, 1).expect("the tick commits"); + assert_eq!(pressure(&kernel, clockwork.reeve, sourced), 1); + + // Repair stops the pressing but never unwrites what accrued. + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::OpenRoute { + route: Ref::Existing(clockwork.gate), + }]), + ); + tick(&mut kernel, 1).expect("the tick commits"); + assert_eq!(pressure(&kernel, clockwork.reeve, sourced), 1); + + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::ResolvePressure { + source: PressureSourceRef::Dependency(DependencyRef::Route(Ref::Existing( + clockwork.gate, + ))), + target: Ref::Existing(clockwork.reeve), + }]), + ); + assert!( + !kernel.state.pressures.contains_key(&clockwork.reeve), + "an emptied target removes its key rather than storing an empty map" + ); + } + + /// The clock moves through exactly one command body. + #[test] + fn time_advances_only_through_advance_time() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "OnlyTick"); + tick(&mut kernel, 5).expect("the tick commits"); + let now = kernel.state.now; + + exercise( + &mut kernel, + clockwork.reeve, + clockwork.threaten, + vec![binding("target", Target::Subject(clockwork.farmer))], + ) + .expect("the threat commits"); + assert_eq!(kernel.state.now, now); + + let snapshot = kernel.snapshot().unwrap(); + let opportunity = opportunity_for(&snapshot, clockwork.farmer); + let caller = CallerId::Controller(opportunity.controller_id); + kernel + .submit( + command( + &snapshot, + CommandId::new(), + caller.clone(), + CommandBody::DeclineDecision { opportunity }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .expect("the decline commits"); + assert_eq!(kernel.state.now, now); + + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::CloseRoute { + route: Ref::Existing(clockwork.gate), + }]), + ); + assert_eq!(kernel.state.now, now); + } + + /// The clock capability is admitted for one body and nothing else. + #[test] + fn the_clock_capability_can_do_nothing_else() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Capability"); + let before = kernel.state.clone(); + let snapshot = kernel.snapshot().unwrap(); + let opportunity = opportunity_for(&snapshot, clockwork.reeve); + + for body in [ + CommandBody::ApproveDraft, + CommandBody::ActivateWorld, + CommandBody::DeclineDecision { + opportunity: opportunity.clone(), + }, + CommandBody::ExerciseDecision { + opportunity, + invocation: DecisionInvocation { + affordance: clockwork.threaten, + bindings: vec![binding("target", Target::Subject(clockwork.farmer))], + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + speech: None, + display: None, + }, + }, + operations(vec![ComponentOp::CloseRoute { + route: Ref::Existing(clockwork.gate), + }]), + ] { + let error = kernel + .submit( + command(&snapshot, CommandId::new(), clock_caller(), body), + &AuthenticatedCaller::fixture(clock_caller()), + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); + } + assert_eq!(kernel.state, before); + tick(&mut kernel, 1).expect("the same caller may tick"); + } + + /// Who may tick, when, and how far. + #[test] + fn advance_time_negatives() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = WorldKernel::create( + directory.path().join("world.cc"), + creation(CommandId::new(), "Negatives"), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + + // There is no time in Draft. + let draft = kernel.snapshot().unwrap(); + let error = kernel + .submit( + command( + &draft, + CommandId::new(), + clock_caller(), + CommandBody::AdvanceTime { + minutes: minutes(1), + }, + ), + &AuthenticatedCaller::fixture(clock_caller()), + ) + .unwrap_err(); + assert!(matches!( + error, + KernelError::WrongPhase { + expected: WorldPhase::Active, + actual: WorldPhase::Draft, + } + )); + + let active = activate(&mut kernel); + // A span is constructor-checked, so a malformed one never reaches a + // command at all. + assert!(TickMinutes::new(0).is_none()); + assert!(TickMinutes::new(super::patch::MAX_ROUTE_COST + 1).is_none()); + + for caller in [ + CallerId::Principal(human_principal()), + CallerId::Controller(active.opportunities[0].controller_id), + ] { + let error = kernel + .submit( + command( + &active, + CommandId::new(), + caller.clone(), + CommandBody::AdvanceTime { + minutes: minutes(1), + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); + } + + // The owner may tick from an interface. + submit_owner( + &mut kernel, + &active, + CommandBody::AdvanceTime { + minutes: minutes(7), + }, + ); + assert_eq!(kernel.state.now, FictionalMinutes(7)); + + // And a span that would overflow the clock is refused rather than + // wrapping. + kernel.state.now = FictionalMinutes(u64::MAX); + let snapshot = kernel.snapshot().unwrap(); + let error = kernel + .submit( + command( + &snapshot, + CommandId::new(), + clock_caller(), + CommandBody::AdvanceTime { + minutes: minutes(1), + }, + ), + &AuthenticatedCaller::fixture(clock_caller()), + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Serialization(_)), "{error:?}"); + } + + /// The whole motion is re-derived at apply, so a forged fulfilment, target, + /// magnitude, or clock reading is one comparison. + #[test] + fn a_forged_motion_does_not_apply() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Forged"); + let to = FictionalMinutes(120); + let honest = clock::derive_motion(&kernel.state, to); + assert!(!honest.fulfilled.is_empty() || !honest.pressed.is_empty()); + + let forgeries = [ + // A forged clock reading. + WorldEffect::TimeAdvanced { + minutes: minutes(120), + to: FictionalMinutes(121), + motion: honest.clone(), + }, + // A fulfilment nothing derived. + WorldEffect::TimeAdvanced { + minutes: minutes(120), + to, + motion: Motion { + fulfilled: vec![clock::RoutineFulfilled { + subject: clockwork.farmer, + key: clockwork.routine, + next_due: FictionalMinutes(9_999), + }], + pressed: honest.pressed.clone(), + }, + }, + // A forged magnitude. + WorldEffect::TimeAdvanced { + minutes: minutes(120), + to, + motion: Motion { + fulfilled: honest.fulfilled.clone(), + pressed: honest + .pressed + .iter() + .map(|written| clock::PressureWritten { + magnitude: PressureMagnitude(written.magnitude.0 + 9), + ..written.clone() + }) + .collect(), + }, + }, + // A pressure row for an untouched subject. + WorldEffect::TimeAdvanced { + minutes: minutes(120), + to, + motion: Motion { + fulfilled: honest.fulfilled.clone(), + pressed: honest + .pressed + .iter() + .cloned() + .chain(std::iter::once(clock::PressureWritten { + target: clockwork.treasury, + source: PressureSource::Subject(clockwork.reeve), + magnitude: PressureMagnitude(5), + })) + .collect(), + }, + }, + ]; + for forged in forgeries { + let mut candidate = kernel.state.clone(); + let error = apply_effect(&mut candidate, CommandId::issue(), &clock_caller(), &forged) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_)), "{error:?}"); + assert_eq!(candidate, kernel.state); + } + + // The honest one applies. + let mut candidate = kernel.state.clone(); + apply_effect( + &mut candidate, + CommandId::issue(), + &clock_caller(), + &WorldEffect::TimeAdvanced { + minutes: minutes(120), + to, + motion: honest, + }, + ) + .expect("the honest motion applies"); + assert_eq!(candidate.now, to); + } + + /// Replay across a tick is exact, and every envelope is idempotent. + #[test] + fn restart_replay_across_a_tick_is_exact() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Replay"); + let world_id = kernel.state.world_id; + + exercise( + &mut kernel, + clockwork.reeve, + clockwork.threaten, + vec![binding("target", Target::Subject(clockwork.farmer))], + ) + .expect("the threat commits"); + tick(&mut kernel, 60).expect("the routine tick commits"); + tick(&mut kernel, 60).expect("the obligation tick commits"); + let snapshot = kernel.snapshot().unwrap(); + let repeat = command( + &snapshot, + CommandId::new(), + CallerId::Principal(owner()), + operations(vec![ComponentOp::DischargeCommitment { + subject: Ref::Existing(clockwork.farmer), + key: clockwork.obligation, + }]), + ); + kernel + .submit(repeat.clone(), &auth_principal(owner())) + .expect("the discharge commits"); + // Discharge removes every pressure row it sourced. + assert_eq!( + pressure( + &kernel, + clockwork.farmer, + PressureSource::Commitment { + subject: clockwork.farmer, + key: clockwork.obligation, + } + ), + 0 + ); + + let before = kernel.state.clone(); + let before_snapshot = kernel.snapshot().unwrap(); + drop(kernel); + let mut replayed = WorldKernel::open(&path, world_id).expect("the store replays"); + assert_eq!(replayed.state, before); + assert_eq!(replayed.snapshot().unwrap(), before_snapshot); + assert!(matches!( + replayed.submit(repeat, &auth_principal(owner())), + Ok(SubmitReceipt::AlreadyApplied(_)) + )); + } + + /// The order is total, deterministic, and never a filter. + #[test] + fn the_attention_order_is_total_and_deterministic() { + let directory = tempfile::tempdir().unwrap(); + let (kernel, clockwork, active) = clock_kernel(directory.path(), "Order"); + let derived = derive_opportunities(&kernel.state).unwrap(); + + let with = |pressures: BTreeMap, + stamps: BTreeMap| + -> Vec { + let mut state = kernel.state.clone(); + state.now = FictionalMinutes(1_000); + state.pressures = pressures + .into_iter() + .map(|(subject, magnitude)| { + ( + subject, + BTreeMap::from([( + PressureSource::Subject(subject), + PressureMagnitude(magnitude), + )]), + ) + }) + .collect(); + state.last_opportunity_at = stamps + .into_iter() + .map(|(subject, stamp)| (subject, FictionalMinutes(stamp))) + .collect(); + order_opportunities(&state, derived.clone()) + .into_iter() + .map(|opportunity| opportunity.scope.subject_id) + .collect() + }; + + // Pressure dominates. + let ordered = with( + BTreeMap::from([(clockwork.farmer, 5), (clockwork.reeve, 3)]), + BTreeMap::new(), + ); + assert_eq!(ordered[0], clockwork.farmer); + assert_eq!(ordered[1], clockwork.reeve); + + // Equal pressure orders by debt, and a subject never attended outranks + // every subject that has. + let stamped: BTreeMap = active + .subjects + .iter() + .map(|subject| (subject.id, 900)) + .collect(); + let mut earlier = stamped.clone(); + earlier.insert(clockwork.treasury, 100); + let ordered = with(BTreeMap::new(), earlier); + assert_eq!(ordered[0], clockwork.treasury); + + // Never a filter: the same length and the same set, whatever the terms. + for pressures in [ + BTreeMap::new(), + BTreeMap::from([(clockwork.reeve, 1)]), + BTreeMap::from([(clockwork.farmer, 9), (clockwork.treasury, 9)]), + ] { + let ordered = with(pressures, stamped.clone()); + assert_eq!(ordered.len(), derived.len()); + assert_eq!( + ordered.iter().copied().collect::>(), + derived + .iter() + .map(|opportunity| opportunity.scope.subject_id) + .collect::>() + ); + } + } + + /// The debt term rotates: with no pressure anywhere, every subject reaches + /// the head within one pass, and standing pressure holds the head until it + /// is resolved. + #[test] + fn every_subject_reaches_the_head_within_bounded_ticks() { + let directory = tempfile::tempdir().unwrap(); + let (kernel, clockwork, _) = clock_kernel(directory.path(), "Rotation"); + let derived = derive_opportunities(&kernel.state).unwrap(); + let count = derived.len(); + + let mut state = kernel.state.clone(); + let mut seen = BTreeSet::new(); + for step in 0..count { + state.now = FictionalMinutes(u64::try_from(step).unwrap() + 1); + let head = order_opportunities(&state, derived.clone())[0] + .scope + .subject_id; + seen.insert(head); + state.last_opportunity_at.insert(head, state.now); + } + assert_eq!(seen.len(), count, "every subject reached the head"); + + // Standing pressure holds the head; the others still rotate among + // themselves once it is resolved. + state.pressures.insert( + clockwork.farmer, + BTreeMap::from([( + PressureSource::Subject(clockwork.reeve), + PressureMagnitude(4), + )]), + ); + for step in 0..count { + state.now = FictionalMinutes(1_000 + u64::try_from(step).unwrap()); + let head = order_opportunities(&state, derived.clone())[0] + .scope + .subject_id; + assert_eq!(head, clockwork.farmer); + state.last_opportunity_at.insert(head, state.now); + } + state.pressures.remove(&clockwork.farmer); + assert_ne!( + order_opportunities(&state, derived.clone())[0] + .scope + .subject_id, + clockwork.farmer + ); + } + + /// Verification 14, first half: a dead end is derived, answered once, and + /// then no longer derived. Nothing clears one but the predicate failing. + #[test] + fn an_unelaborated_destination_is_derived_and_answered_exactly_once() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "DeadEnd"); + let boundaries = derive_boundaries(&kernel.state).unwrap(); + let destinations: Vec<_> = boundaries + .iter() + .filter(|boundary| matches!(boundary, CausalBoundary::UnelaboratedDestination { .. })) + .collect(); + assert_eq!(destinations.len(), 1); + let answered = destinations[0].clone(); + assert!(matches!( + answered, + CausalBoundary::UnelaboratedDestination { route, place, .. } + if route == clockwork.gate && place == clockwork.dead_end + )); + + let snapshot = kernel.snapshot().unwrap(); + assert!(snapshot.boundaries.contains(&answered)); + submit_owner( + &mut kernel, + &snapshot, + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered.clone())), + patch: WorldPatch { + declarations: vec![Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("shed"), + label: "The Roadside Shed".into(), + kind: EntityKind::Place, + container: Some(Ref::Existing(clockwork.dead_end)), + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ); + assert!( + !derive_boundaries(&kernel.state) + .unwrap() + .contains(&answered) + ); + + // Answering it again names a boundary the kernel no longer derives. + let snapshot = kernel.snapshot().unwrap(); + let error = kernel + .submit( + command( + &snapshot, + CommandId::new(), + CallerId::Principal(owner()), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered)), + patch: WorldPatch { + declarations: vec![Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("byre"), + label: "The Roadside Byre".into(), + kind: EntityKind::Place, + container: Some(Ref::Existing(clockwork.dead_end)), + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ), + &auth_principal(owner()), + ) + .unwrap_err(); + assert!(matches!(error, KernelError::AnswerNotDerived), "{error:?}"); + } + + /// A promise the counterparty can neither command nor litigate is a missing + /// structure, and either repair clears it. A goal never derives one. + #[test] + fn a_commitment_with_no_authority_or_redress_derives_missing_structure() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Structure"); + let missing = CausalBoundary::MissingStructure { + subject: clockwork.farmer, + key: clockwork.obligation, + scope: BoundaryDigest(String::new()), + }; + let derives = |kernel: &WorldKernel| { + derive_boundaries(&kernel.state) + .unwrap() + .into_iter() + .any(|boundary| match (&boundary, &missing) { + ( + CausalBoundary::MissingStructure { subject, key, .. }, + CausalBoundary::MissingStructure { + subject: expected_subject, + key: expected_key, + .. + }, + ) => subject == expected_subject && key == expected_key, + _ => false, + }) + }; + assert!(derives(&kernel)); + // A goal is a promise to oneself and needs no forum. + assert!(!derive_boundaries(&kernel.state).unwrap().iter().any( + |boundary| matches!(boundary, CausalBoundary::MissingStructure { key, .. } if *key == clockwork.goal) + )); + + // Jurisdiction over the promisor's ground clears it. + let snapshot = kernel.snapshot().unwrap(); + let grant = ComponentOp::GrantAuthority { + holder: Ref::Existing(clockwork.treasury), + grant: AuthorityGrantRef { + kind: AuthorityKindName("command".into()), + over: AuthorityTargetRef::PlaceSubtree(Ref::Existing(clockwork.yard)), + }, + }; + submit_owner(&mut kernel, &snapshot, operations(vec![grant.clone()])); + assert!(!derives(&kernel)); + + // Revoke it, and a forum whose standing covers the counterparty clears + // it the other way. + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::RevokeAuthority { + holder: Ref::Existing(clockwork.treasury), + grant: AuthorityGrantRef { + kind: AuthorityKindName("command".into()), + over: AuthorityTargetRef::PlaceSubtree(Ref::Existing(clockwork.yard)), + }, + }]), + ); + assert!(derives(&kernel)); + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::OpenForum { + grievance: GrievanceKindName("debt".into()), + forum: Ref::Existing(clockwork.reeve), + standing: AuthorityTargetRef::Subject(Ref::Existing(clockwork.treasury)), + }]), + ); + assert!(!derives(&kernel)); + } + + /// Verification 14, second half: an answer must be derived, and the commit + /// must satisfy what it answered. + #[test] + fn an_answer_must_be_derived_and_must_be_satisfied() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Answers"); + let before = kernel.state.clone(); + let declaring = |answers: Option, handle: &str| CommandBody::AdmitPatch { + answers, + patch: WorldPatch { + declarations: vec![Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(handle), + label: "A Later Room".into(), + kind: EntityKind::Place, + container: None, + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }; + let refuse = |kernel: &mut WorldKernel, body: CommandBody| { + let snapshot = kernel.snapshot().unwrap(); + kernel + .submit( + command( + &snapshot, + CommandId::new(), + CallerId::Principal(owner()), + body, + ), + &auth_principal(owner()), + ) + .unwrap_err() + }; + + // Declaring in Active without answering. + assert!(matches!( + refuse(&mut kernel, declaring(None, "unanswered")), + KernelError::AnswerRequired + )); + // The two declared-but-never-derived variants. + for boundary in [ + CausalBoundary::PolityInCausalRange { + subject: clockwork.reeve, + scope: BoundaryDigest(String::new()), + }, + CausalBoundary::IndividuationRequired { + population: clockwork.reeve, + scope: BoundaryDigest(String::new()), + }, + ] { + assert!(matches!( + refuse( + &mut kernel, + declaring(Some(PatchAnswer::Boundary(boundary)), "underived") + ), + KernelError::AnswerNotDerived + )); + } + // A jurisdiction with no deficit. + assert!(matches!( + refuse( + &mut kernel, + declaring( + Some(PatchAnswer::Deficit(JurisdictionKey::Uncovered)), + "no-deficit" + ) + ), + KernelError::AnswerNotDerived + )); + // A derived boundary answered by a patch that leaves the predicate + // holding. + let destination = derive_boundaries(&kernel.state) + .unwrap() + .into_iter() + .find(|boundary| matches!(boundary, CausalBoundary::UnelaboratedDestination { .. })) + .expect("the dead end"); + assert!(matches!( + refuse( + &mut kernel, + declaring(Some(PatchAnswer::Boundary(destination)), "elsewhere") + ), + KernelError::AnswerNotSatisfied + )); + assert_eq!(kernel.state, before); + + // Draft answers nothing. + let directory = tempfile::tempdir().unwrap(); + let mut draft_kernel = WorldKernel::create( + directory.path().join("world.cc"), + creation(CommandId::new(), "Draft"), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + assert!(matches!( + refuse( + &mut draft_kernel, + declaring( + Some(PatchAnswer::Deficit(JurisdictionKey::Uncovered)), + "in-draft" + ) + ), + KernelError::AnswerNotDerived + )); + } + + fn creation_with_intent( + id: CommandId, + title: &str, + intent: WorldScaleIntentRef, + ) -> CreateWorld { + let mut creation = creation(id, title); + creation.scale_intent = intent; + creation + } + + fn intent(root: &str, persons: u32, permille: u32) -> WorldScaleIntentRef { + WorldScaleIntentRef { + targets: BTreeMap::from([(SubjectKind::Person, persons)]), + jurisdictions: BTreeMap::from([(DraftHandle::new(root), permille)]), + } + } + + /// Verification 22, first half: only a qualified subject reduces the + /// deficit, and `Goal` carries the whole discrimination. + #[test] + fn a_subject_counts_toward_the_deficit_only_when_qualified() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = WorldKernel::create( + directory.path().join("world.cc"), + creation_with_intent( + CommandId::new(), + "Scale", + intent(super::tests::COMMONS, 3, 1000), + ), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let commons = kernel + .state + .scale_intent + .jurisdictions + .keys() + .copied() + .next() + .expect("the declared root"); + let active = activate(&mut kernel); + let counted = active + .subjects + .iter() + .find(|subject| subject.kind == SubjectKind::Person) + .expect("the fixture world has a person") + .id; + + let deficit = |kernel: &WorldKernel, jurisdiction: JurisdictionKey| { + derive_scale_deficit(&kernel.state) + .unwrap() + .into_iter() + .find(|row| row.jurisdiction == jurisdiction && row.kind == SubjectKind::Person) + }; + let row = deficit(&kernel, JurisdictionKey::PlaceSubtree(commons)) + .expect("a target of three persons"); + assert_eq!((row.target, row.qualified, row.deficit), (3, 0, 3)); + + // A controller and a grant are not enough; a `Goal` is what counts. + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::CreateCommitment { + subject: Ref::Existing(counted), + counterparty: None, + kind: CommitmentKind::Goal, + due: FictionalMinutes(500), + period: None, + checks: Vec::new(), + statement: Statement::new("What was promised, as the promisor would say it.").unwrap(), + }]), + ); + let goal = *kernel.state.commitments[&counted] + .keys() + .next() + .expect("the goal"); + let row = deficit(&kernel, JurisdictionKey::PlaceSubtree(commons)).unwrap(); + assert_eq!((row.target, row.qualified, row.deficit), (3, 1, 2)); + + // Discharging it raises the deficit again. + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::DischargeCommitment { + subject: Ref::Existing(counted), + key: goal, + }]), + ); + let row = deficit(&kernel, JurisdictionKey::PlaceSubtree(commons)).unwrap(); + assert_eq!((row.target, row.qualified, row.deficit), (3, 0, 3)); + } + + /// A qualifying subject standing somewhere no declared root covers still + /// counts, in the `Uncovered` row, rather than vanishing from the deficit + /// entirely: the count is total over every qualifying subject. + #[test] + fn a_subject_placed_outside_every_root_counts_as_uncovered() { + let directory = tempfile::tempdir().unwrap(); + let mut creation = creation_with_intent( + CommandId::new(), + "Uncovered", + intent(super::tests::COMMONS, 3, 1000), + ); + creation + .patch + .declarations + .push(Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("elsewhere"), + label: "The Elsewhere".into(), + kind: EntityKind::Place, + container: None, + })); + creation + .patch + .declarations + .push(Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("bridge"), + label: "The Elsewhere Bridge".into(), + from: Ref::Draft(DraftHandle::new(super::tests::COMMONS)), + to: Ref::Draft(DraftHandle::new("elsewhere")), + access: AccessKind::Public, + cost: Cost(1), + })); + let mut kernel = WorldKernel::create( + directory.path().join("world.cc"), + creation, + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let active = activate(&mut kernel); + let subject_count = kernel.state.subjects.len() as u32; + assert_eq!(subject_count, 3, "the base fixture declares three subjects"); + + // Every subject qualifies, so the deficit's row counts must sum to + // the whole subject count. + let goal = |subject: SubjectId| ComponentOp::CreateCommitment { + subject: Ref::Existing(subject), + counterparty: None, + kind: CommitmentKind::Goal, + due: FictionalMinutes(500), + period: None, + checks: Vec::new(), + statement: Statement::new("What was promised, as the promisor would say it.").unwrap(), + }; + let subject_ids: Vec = + active.subjects.iter().map(|subject| subject.id).collect(); + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(subject_ids.iter().copied().map(goal).collect()), + ); + + let moved = active + .subjects + .iter() + .find(|subject| subject.kind == SubjectKind::Person) + .expect("the fixture world has a person") + .id; + let bridge = active + .routes + .iter() + .find(|route| route.label == "The Elsewhere Bridge") + .expect("the declared route") + .id; + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::Relocate { + subject: Ref::Existing(moved), + via: Ref::Existing(bridge), + }]), + ); + + let rows = derive_scale_deficit(&kernel.state).unwrap(); + let uncovered = rows + .iter() + .find(|row| { + row.jurisdiction == JurisdictionKey::Uncovered && row.kind == SubjectKind::Person + }) + .expect("the relocated subject counts as uncovered"); + assert_eq!(uncovered.qualified, 1); + + let counted_total: u32 = rows.iter().map(|row| row.qualified).sum(); + assert_eq!( + counted_total, subject_count, + "the deficit is total over every qualifying subject" + ); + } + + /// Weights distribute the target and never raise it, and a root must be a + /// declared place. + #[test] + fn scale_weights_distribute_and_never_raise() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let over_whole = WorldScaleIntentRef { + targets: BTreeMap::from([(SubjectKind::Person, 10)]), + jurisdictions: BTreeMap::from([ + (DraftHandle::new(super::tests::COMMONS), 700), + (DraftHandle::new("human"), 400), + ]), + }; + let Err(error) = WorldKernel::create( + &path, + creation_with_intent(CommandId::new(), "TooMuch", over_whole), + &auth_principal(owner()), + ) else { + panic!("a genesis intent over the whole was admitted"); + }; + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected genesis patch"); + }; + assert!(mismatches.contains(&Mismatch::ScaleWeightsExceedWhole)); + // `human` is a subject handle, not a place. + assert!(mismatches.contains(&Mismatch::UnknownJurisdictionRoot { + handle: DraftHandle::new("human"), + })); + + // Half the whole distributes half the target, rounded down. + let mut kernel = WorldKernel::create( + &path, + creation_with_intent( + CommandId::new(), + "Half", + intent(super::tests::COMMONS, 5, 500), + ), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + activate(&mut kernel); + let rows = derive_scale_deficit(&kernel.state).unwrap(); + let commons_target: u32 = rows + .iter() + .filter(|row| matches!(row.jurisdiction, JurisdictionKey::PlaceSubtree(_))) + .map(|row| row.target) + .sum(); + assert_eq!(commons_target, 2); + assert!(commons_target <= 5); + } + + /// A rejected patch mutates nothing, so the deficit it would have reduced + /// stays visible. + #[test] + fn a_rejected_patch_leaves_the_deficit_unchanged_and_visible() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = WorldKernel::create( + directory.path().join("world.cc"), + creation_with_intent( + CommandId::new(), + "Rejected", + intent(super::tests::COMMONS, 3, 1000), + ), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let active = activate(&mut kernel); + let before = derive_scale_deficit(&kernel.state).unwrap(); + let subjects: Vec = active + .subjects + .iter() + .filter(|subject| subject.kind == SubjectKind::Person) + .map(|subject| subject.id) + .collect(); + let goal = |subject: SubjectId, due: u64| ComponentOp::CreateCommitment { + subject: Ref::Existing(subject), + counterparty: None, + kind: CommitmentKind::Goal, + due: FictionalMinutes(due), + period: None, + checks: Vec::new(), + statement: Statement::new("What was promised, as the promisor would say it.").unwrap(), + }; + + // One of the two goals is born past due. + assert_eq!( + reject_owner( + &mut kernel, + &active, + operations(vec![goal(subjects[0], 500), goal(subjects[1], 0)]), + ), + vec![Mismatch::CommitmentDueInThePast { operation: 1 }] + ); + assert_eq!(derive_scale_deficit(&kernel.state).unwrap(), before); + + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![goal(subjects[0], 500), goal(subjects[1], 600)]), + ); + let after = derive_scale_deficit(&kernel.state).unwrap(); + let total = |rows: &[ScaleDeficitRow]| -> u32 { rows.iter().map(|row| row.deficit).sum() }; + assert_eq!(total(&after) + 2, total(&before)); + } + + /// Every commitment shape check, in one complete sorted set. + #[test] + fn commitment_declaration_negatives() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, active) = clock_kernel(directory.path(), "Shapes"); + let before = kernel.state.clone(); + let create = |kind: CommitmentKind, + counterparty: Option, + due: u64, + period: Option, + checks: Vec| { + ComponentOp::CreateCommitment { + subject: Ref::Existing(clockwork.farmer), + counterparty: counterparty.map(Ref::Existing), + kind, + due: FictionalMinutes(due), + period, + checks, + statement: Statement::new("What was promised, as the promisor would say it.").unwrap(), + } + }; + + assert_eq!( + reject_owner( + &mut kernel, + &active, + operations(vec![ + // 0: a routine with no period. + create(CommitmentKind::Routine, None, 500, None, Vec::new()), + // 1: a goal with a period. + create( + CommitmentKind::Goal, + None, + 500, + Some(minutes(10)), + Vec::new() + ), + // 2: checks on a non-routine. + create( + CommitmentKind::Obligation, + Some(clockwork.treasury), + 500, + None, + vec![PreconditionRef::Present { + at: Ref::Existing(clockwork.yard), + }], + ), + // 3: born past due. + create( + CommitmentKind::Obligation, + Some(clockwork.treasury), + 0, + None, + Vec::new() + ), + // 4: a promise to oneself with a counterparty. + create( + CommitmentKind::Obligation, + Some(clockwork.farmer), + 500, + None, + Vec::new() + ), + // 5: a goal with a counterparty. + create( + CommitmentKind::Goal, + Some(clockwork.treasury), + 500, + None, + Vec::new() + ), + // 6: a discharge of a key nobody holds. + ComponentOp::DischargeCommitment { + subject: Ref::Existing(clockwork.farmer), + key: CommitmentKey { + command: CommandId::new(), + index: 0, + }, + }, + ]), + ), + { + let mut expected = vec![ + Mismatch::CommitmentPeriodMismatch { operation: 0 }, + Mismatch::CommitmentPeriodMismatch { operation: 1 }, + Mismatch::ChecksOnNonRoutine { operation: 2 }, + Mismatch::CommitmentDueInThePast { operation: 3 }, + Mismatch::SelfCommitment { operation: 4 }, + Mismatch::GoalWithCounterparty { operation: 5 }, + Mismatch::UnknownCommitment { operation: 6 }, + ]; + expected.sort(); + expected + } + ); + assert_eq!(kernel.state, before); + + // Repairing exactly those commits. + submit_owner( + &mut kernel, + &active, + operations(vec![ + create( + CommitmentKind::Routine, + None, + 500, + Some(minutes(10)), + Vec::new(), + ), + create(CommitmentKind::Goal, None, 500, None, Vec::new()), + create( + CommitmentKind::Obligation, + Some(clockwork.treasury), + 500, + None, + Vec::new(), + ), + ComponentOp::DischargeCommitment { + subject: Ref::Existing(clockwork.farmer), + key: clockwork.routine, + }, + ]), + ); + assert!( + !kernel.state.commitments[&clockwork.farmer].contains_key(&clockwork.routine), + "the discharge removed the routine" + ); + } + + /// `Committed` reads the actor's own commitments, and a discharge mid-flight + /// rejects the promisor's bound proposal while the counterparty's own + /// invocation fails at admission. + #[test] + fn committed_reads_the_actors_own_commitments() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Committed"); + + // The reeve promised the treasury nothing. + let error = exercise( + &mut kernel, + clockwork.reeve, + clockwork.deliver, + vec![binding("creditor", Target::Subject(clockwork.treasury))], + ) + .unwrap_err(); + assert!(matches!( + error, + KernelError::ActionRejected(ref mismatches) + if *mismatches == vec![ActionMismatch::NotCommitted { precondition: 0 }] + )); + + // The farmer did, so the entry commits and mints a second obligation + // whose due date the kernel computed. + let before = kernel.state.commitments[&clockwork.farmer].len(); + exercise( + &mut kernel, + clockwork.farmer, + clockwork.deliver, + vec![binding("creditor", Target::Subject(clockwork.treasury))], + ) + .expect("the delivery commits"); + assert_eq!( + kernel.state.commitments[&clockwork.farmer].len(), + before + 1 + ); + + // A proposal bound before a discharge is rejected as a scope change for + // the promisor: `Committed` reads commitments, so the digest binds them. + let snapshot = kernel.snapshot().unwrap(); + let stale = opportunity_for(&snapshot, clockwork.farmer); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::DischargeCommitment { + subject: Ref::Existing(clockwork.farmer), + key: clockwork.obligation, + }]), + ); + let caller = CallerId::Controller(stale.controller_id); + let after = kernel.snapshot().unwrap(); + let error = kernel + .submit( + command( + &after, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + opportunity: stale, + invocation: DecisionInvocation { + affordance: clockwork.deliver, + bindings: vec![binding( + "creditor", + Target::Subject(clockwork.treasury), + )], + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + speech: None, + display: None, + }, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .unwrap_err(); + assert!( + matches!(error, KernelError::ScopeChanged { .. }), + "{error:?}" + ); + } + + /// A tick that only advances pressure moves nobody's scope digest; a tick + /// that fulfils a routine moves exactly that subject's. + #[test] + fn a_pressure_tick_moves_no_scope_digest_and_a_routine_tick_moves_one() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Digests"); + let digests = |kernel: &WorldKernel| -> BTreeMap { + derive_opportunities(&kernel.state) + .unwrap() + .into_iter() + .map(|opportunity| (opportunity.scope.subject_id, opportunity.scope_digest)) + .collect() + }; + + // Past the obligation and the goal, but the routine is blocked out of + // the yard first so only pressure moves. + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::DischargeCommitment { + subject: Ref::Existing(clockwork.farmer), + key: clockwork.routine, + }]), + ); + let before = digests(&kernel); + tick(&mut kernel, 200).expect("the tick commits"); + assert!(!kernel.state.pressures.is_empty(), "the tick pressed"); + assert_eq!(digests(&kernel), before, "pressure binds no proposal"); + + // A routine fulfilment moves exactly its own subject's digest. + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::CreateCommitment { + subject: Ref::Existing(clockwork.reeve), + counterparty: None, + kind: CommitmentKind::Routine, + due: FictionalMinutes(500), + period: Some(minutes(60)), + checks: Vec::new(), + statement: Statement::new("What was promised, as the promisor would say it.").unwrap(), + }]), + ); + let before = digests(&kernel); + tick(&mut kernel, 400).expect("the tick commits"); + let after = digests(&kernel); + for (subject, digest) in &before { + if *subject == clockwork.reeve { + assert_ne!(after[subject], *digest, "the fulfilling subject rebinds"); + } else { + assert_eq!(after[subject], *digest, "everyone else still commits"); + } + } + } + + /// Soul falsification: the attention order is total on `SubjectId` when + /// pressure and debt tie, and it is the same order for every input + /// permutation. `sort_by_key` is stable, so an order that leaned on its + /// input's order would pass a single-vector test and drift with map + /// iteration. + #[test] + fn soul_the_attention_order_is_id_total_under_every_input_permutation() { + let directory = tempfile::tempdir().unwrap(); + let (kernel, clockwork, _) = clock_kernel(directory.path(), "Ties"); + let mut state = kernel.state.clone(); + state.now = FictionalMinutes(5_000); + // Equal pressure and an equal stamp on every subject: only the id can + // decide. + for subject_id in state.subjects.keys().copied().collect::>() { + state.pressures.insert( + subject_id, + BTreeMap::from([( + PressureSource::Subject(clockwork.reeve), + PressureMagnitude(7), + )]), + ); + state + .last_opportunity_at + .insert(subject_id, FictionalMinutes(400)); + } + let derived = derive_opportunities(&state).unwrap(); + assert!( + derived.len() >= 3, + "the fixture ties at least three subjects" + ); + let expected: Vec = order_opportunities(&state, derived.clone()) + .into_iter() + .map(|opportunity| opportunity.scope.subject_id) + .collect(); + let mut ascending = expected.clone(); + ascending.sort_unstable(); + assert_eq!(expected, ascending, "an equal-key tie is broken by id"); + + // Every rotation and the full reversal produce the same order. + for shift in 0..derived.len() { + let mut permuted = derived.clone(); + permuted.rotate_left(shift); + let mut reversed = permuted.clone(); + reversed.reverse(); + for candidate in [permuted, reversed] { + let ordered: Vec = order_opportunities(&state, candidate) + .into_iter() + .map(|opportunity| opportunity.scope.subject_id) + .collect(); + assert_eq!(ordered, expected, "the order read its input's order"); + } + } + } + + /// Soul falsification of the admission ruling: in Active a patch that only + /// changes components answers nothing, a patch that declares or admits + /// evidence must answer, and the answer gate closes before the resolver + /// ever runs. + #[test] + fn soul_an_active_patch_answers_only_when_it_elaborates() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Elaborate"); + + // Component-only, no answer: admitted. + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::AdvancePressure { + source: PressureSourceRef::Subject(Ref::Existing(clockwork.reeve)), + target: Ref::Existing(clockwork.farmer), + by: PressureMagnitude(2), + }]), + ); + assert_eq!( + pressure( + &kernel, + clockwork.farmer, + PressureSource::Subject(clockwork.reeve) + ), + 2 + ); + + let refuse = |kernel: &mut WorldKernel, body: CommandBody| { + let snapshot = kernel.snapshot().unwrap(); + kernel + .submit( + command( + &snapshot, + CommandId::new(), + CallerId::Principal(owner()), + body, + ), + &auth_principal(owner()), + ) + .unwrap_err() + }; + + // Evidence alone is elaboration too, so it answers. + let evidence_only = CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations: Vec::new(), + evidence: vec![EvidenceRef::new("soul://evidence-only")], + }, + }; + assert!(matches!( + refuse(&mut kernel, evidence_only), + KernelError::AnswerRequired + )); + + // The gate is ahead of the resolver: a declaring patch that is also + // structurally broken is refused for the missing answer, not for the + // mismatch it would otherwise return. + let broken = CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("orphan"), + label: "An Orphan Room".into(), + kind: EntityKind::Place, + container: Some(Ref::Draft(DraftHandle::new("nowhere"))), + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }; + assert!( + matches!(refuse(&mut kernel, broken), KernelError::AnswerRequired), + "the resolver ran before the answer gate" + ); + + // A derived answer that the patch satisfies commits, and the boundary + // is gone afterwards. + let answered = derive_boundaries(&kernel.state) + .unwrap() + .into_iter() + .find(|boundary| matches!(boundary, CausalBoundary::UnelaboratedDestination { .. })) + .expect("the dead end"); + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered.clone())), + patch: WorldPatch { + declarations: vec![Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("cairn"), + label: "A Roadside Cairn".into(), + kind: EntityKind::Place, + container: Some(Ref::Existing(clockwork.dead_end)), + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ); + assert!( + !derive_boundaries(&kernel.state) + .unwrap() + .contains(&answered), + "the answered boundary is still derived" + ); + } + + /// Soul falsification: pressure magnitude cannot overflow or go negative, + /// and zero is spelled by absence at both ends. + #[test] + fn soul_pressure_saturates_and_never_underflows() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Saturate"); + let sourced = PressureSource::Commitment { + subject: clockwork.farmer, + key: clockwork.obligation, + }; + + // A tick over a magnitude already at the ceiling saturates rather than + // wrapping. + let mut brimming = kernel.state.clone(); + brimming.pressures.insert( + clockwork.farmer, + BTreeMap::from([(sourced, PressureMagnitude(u32::MAX))]), + ); + let motion = clock::derive_motion(&brimming, FictionalMinutes(LATE_DUE)); + let written = motion + .pressed + .iter() + .find(|written| written.source == sourced) + .expect("the past-due obligation pressed"); + assert_eq!(written.magnitude, PressureMagnitude(u32::MAX)); + + // Reducing by more than the row holds removes it instead of wrapping. + tick(&mut kernel, u32::try_from(LATE_DUE).unwrap()).expect("the tick commits"); + assert_eq!(pressure(&kernel, clockwork.farmer, sourced), 1); + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::ReducePressure { + source: PressureSourceRef::Commitment { + subject: Ref::Existing(clockwork.farmer), + key: clockwork.obligation, + }, + target: Ref::Existing(clockwork.farmer), + by: PressureMagnitude(9), + }]), + ); + assert_eq!(pressure(&kernel, clockwork.farmer, sourced), 0); + assert!( + !kernel.state.pressures.contains_key(&clockwork.farmer), + "an emptied target keeps no empty inner map" + ); + + // `pressure_total` and `attention_debt` are derived, never stored. + assert_eq!(pressure_total(&kernel.state, clockwork.farmer), 0); + assert_eq!( + attention_debt(&kernel.state, clockwork.treasury), + u64::MAX, + "a subject never attended carries the whole debt" + ); + + // Resolving an absent row changes nothing and is refused. + let snapshot = kernel.snapshot().unwrap(); + let mismatches = reject_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::ResolvePressure { + source: PressureSourceRef::Commitment { + subject: Ref::Existing(clockwork.farmer), + key: clockwork.obligation, + }, + target: Ref::Existing(clockwork.farmer), + }]), + ); + assert_eq!( + mismatches, + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + } + + /// Soul falsification: `now` is in no scope preimage. A tick with nothing + /// due moves the clock and not one subject's digest. + #[test] + fn soul_a_clock_only_tick_moves_no_scope_digest() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, _, _) = clock_kernel(directory.path(), "ClockOnly"); + let digests = |kernel: &WorldKernel| -> BTreeMap { + derive_opportunities(&kernel.state) + .unwrap() + .into_iter() + .map(|opportunity| (opportunity.scope.subject_id, opportunity.scope_digest)) + .collect() + }; + let before = digests(&kernel); + let before_now = kernel.state.now; + + // Short of every due date in the fixture. + tick(&mut kernel, 10).expect("the tick commits"); + assert_eq!(kernel.state.now, FictionalMinutes(before_now.0 + 10)); + assert!(kernel.state.pressures.is_empty()); + assert_eq!(digests(&kernel), before, "the clock entered a scope digest"); + } + + /// Soul falsification: the authored scale target is written once by genesis + /// and by no Active lane. `AdmitPatch` resolves with no intent at all, so + /// there is no shape for an Active rewrite to take. + #[test] + fn soul_the_scale_intent_is_written_once_by_genesis() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = WorldKernel::create( + directory.path().join("world.cc"), + creation_with_intent( + CommandId::new(), + "WriteOnce", + intent(super::tests::COMMONS, 3, 1000), + ), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let active = activate(&mut kernel); + let authored = kernel.state.scale_intent.clone(); + assert!(!authored.jurisdictions.is_empty()); + + let subject = active + .subjects + .iter() + .find(|subject| subject.kind == SubjectKind::Person) + .expect("a person") + .id; + let body = operations(vec![ComponentOp::CreateCommitment { + subject: Ref::Existing(subject), + counterparty: None, + kind: CommitmentKind::Goal, + due: FictionalMinutes(500), + period: None, + checks: Vec::new(), + statement: Statement::new("What was promised, as the promisor would say it.").unwrap(), + }]); + // The Active resolver is handed no intent, so the resolved patch cannot + // carry one. + let CommandBody::AdmitPatch { patch, .. } = &body else { + panic!("the operations helper builds an admitted patch"); + }; + let resolved = + patch::resolve_patch(&kernel.state, CommandId::new(), patch, None, None).expect("resolves"); + assert!( + resolved.scale_intent.is_none(), + "an Active patch resolved a scale intent" + ); + + submit_owner(&mut kernel, &active, body); + assert_eq!(kernel.state.scale_intent, authored); + } + + // ---- lens weights: world data, genesis, and the owner command -------- + + fn every_lens_at_zero() -> LensWeights { + LensWeights::new(Lens::ALL.into_iter().map(|lens| (lens, 0)).collect()) + } + + #[test] + fn genesis_writes_the_lens_weights_it_was_given() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let given = LensWeights::new(BTreeMap::from([(Lens::Patina, 2), (Lens::Numen, 1)])); + let mut input = creation(CommandId::new(), "Flavored"); + input.lens_weights = given.clone(); + let (kernel, _) = WorldKernel::create(&path, input, &auth_principal(owner())).unwrap(); + let created = kernel.snapshot().unwrap(); + assert_eq!(created.lens_weights, given); + assert_eq!(kernel.state.lens_weights, given); + + let world_id = created.world_id; + drop(kernel); + let replayed = WorldKernel::open(&path, world_id).unwrap(); + assert_eq!(replayed.snapshot().unwrap(), created); + assert_eq!(replayed.state.state_digest, created.state_digest); + } + + #[test] + fn a_genesis_lens_set_that_never_draws_is_refused() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let mut input = creation(CommandId::new(), "Flavorless"); + input.lens_weights = every_lens_at_zero(); + let Err(error) = WorldKernel::create(&path, input, &auth_principal(owner())) else { + panic!("a genesis lens set that never draws was admitted"); + }; + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected genesis patch, got {error:?}"); + }; + assert_eq!(mismatches, vec![Mismatch::LensWeightsNeverDraw]); + assert!(!path.exists(), "a refused genesis wrote a world file"); + + // The same creation with one real weight among the zeros is admitted. + let mut input = creation(CommandId::new(), "Flavorless"); + let mut weights = BTreeMap::from_iter(every_lens_at_zero().iter()); + weights.insert(Lens::Veil, 1); + input.lens_weights = LensWeights::new(weights); + WorldKernel::create(&path, input, &auth_principal(owner())).expect("one nonzero weight"); + } + + // ---- PA.f26: the genesis lane obeys `require_ruler` too ------------ + + /// PA.f26: `prepare_creation` and `WorldState::genesis` both call + /// `require_ruler` exactly where every other admission lane does. A + /// creation patch that carries a `Ruled` fact is refused before a world + /// is ever written. + #[test] + fn a_genesis_patch_carrying_a_ruled_fact_is_refused() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let mut input = creation(CommandId::new(), "RuledGenesis"); + input + .patch + .declarations + .push(Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("rule"), + label: "The Ruling".into(), + statement: Statement::new("Stated by the table.").unwrap(), + standing: FactStandingRef::Ruled, + })); + let Err(error) = WorldKernel::create(&path, input, &auth_principal(owner())) else { + panic!("a genesis patch carrying a Ruled fact was admitted"); + }; + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::RuledWithoutAuthority { + site: patch::Site::Declaration(DraftHandle::new("rule")), + })), + "{error:?}" + ); + assert!(!path.exists(), "a refused genesis wrote a world file"); + } + + /// PA.f26, the `Mint` half: a creation patch that carries a `Mint` is + /// refused the same way. + #[test] + fn a_genesis_patch_carrying_a_mint_is_refused() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let mut input = creation(CommandId::new(), "MintGenesis"); + input + .patch + .declarations + .push(super::tests::resource("loot", "Roadside Loot")); + input.patch.operations.push(ComponentOp::Mint { + holder: Ref::Draft(DraftHandle::new("human")), + resource: Ref::Draft(DraftHandle::new("loot")), + qty: Quantity(4), + }); + let Err(error) = WorldKernel::create(&path, input, &auth_principal(owner())) else { + panic!("a genesis patch carrying a Mint was admitted"); + }; + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::RuledWithoutAuthority { + site: patch::Site::Operation(0), + })), + "{error:?}" + ); + assert!(!path.exists(), "a refused genesis wrote a world file"); + } + + /// PA.f26: `WorldState::genesis` re-decides `require_ruler` on its own + /// terms, independent of `prepare_creation` — that is what protects + /// journal replay of a stored genesis commit, not only a freshly + /// admitted one. Called directly, bypassing `prepare_creation` entirely, + /// so this cannot be satisfied by `prepare_creation`'s own check. + #[test] + fn genesis_itself_refuses_a_ruled_fact_and_a_mint() { + let world_id = WorldId::issue(); + let mut input = creation(CommandId::new(), "GenesisRuleDirect"); + input + .patch + .declarations + .push(Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("rule"), + label: "The Ruling".into(), + statement: Statement::new("Stated by the table.").unwrap(), + standing: FactStandingRef::Ruled, + })); + let title = normalize_title(&input.title).unwrap(); + let resolved = patch::resolve_patch( + &WorldState::empty(world_id, input.owner.clone(), title.clone(), None), + input.id, + &input.patch, + Some(&input.scale_intent), + Some(&input.lens_weights), + ) + .expect("the resolver is actor-blind and accepts a Ruled fact"); + let effect = WorldEffect::WorldCreated { + owner: input.owner.clone(), + title, + brief: input.brief.clone(), + resolved, + }; + let error = WorldState::genesis(world_id, &input, &effect).unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_)), "{error:?}"); + + let world_id = WorldId::issue(); + let mut input = creation(CommandId::new(), "GenesisMintDirect"); + input + .patch + .declarations + .push(super::tests::resource("loot", "Roadside Loot")); + input.patch.operations.push(ComponentOp::Mint { + holder: Ref::Draft(DraftHandle::new("human")), + resource: Ref::Draft(DraftHandle::new("loot")), + qty: Quantity(4), + }); + let title = normalize_title(&input.title).unwrap(); + let resolved = patch::resolve_patch( + &WorldState::empty(world_id, input.owner.clone(), title.clone(), None), + input.id, + &input.patch, + Some(&input.scale_intent), + Some(&input.lens_weights), + ) + .expect("the resolver is actor-blind and accepts a Mint"); + let effect = WorldEffect::WorldCreated { + owner: input.owner.clone(), + title, + brief: input.brief.clone(), + resolved, + }; + let error = WorldState::genesis(world_id, &input, &effect).unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_)), "{error:?}"); + } + + /// Soul falsification, the lens twin of the scale intent's write-once + /// test: an Active patch resolves no weights; only the owner's + /// `SetLensWeights` replaces them, in Draft and in Active; every other + /// caller is `Unauthorized`; a set that never draws is refused; and + /// `apply_effect` re-decides the owner against a hand-built effect. + #[test] + fn soul_the_lens_weights_are_replaced_only_by_the_owner_command() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, _) = WorldKernel::create( + directory.path().join("world.cc"), + creation(CommandId::new(), "Owner Flavor"), + &auth_principal(owner()), + ) + .unwrap(); + let draft_weights = LensWeights::new(BTreeMap::from([ + (Lens::Patina, 0), + (Lens::Charter, 3), + (Lens::Ledger, 1), + ])); + let draft = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &draft, + CommandBody::SetLensWeights { + weights: draft_weights.clone(), + }, + ); + assert_eq!(kernel.state.revision, draft.revision + 1); + assert_eq!(kernel.state.lens_weights, draft_weights); + + let active = activate(&mut kernel); + let active_weights = LensWeights::new(BTreeMap::from([ + (Lens::Hearth, 5), + (Lens::Tangle, 0), + (Lens::Ember, 2), + ])); + submit_owner( + &mut kernel, + &active, + CommandBody::SetLensWeights { + weights: active_weights.clone(), + }, + ); + assert_eq!(kernel.state.revision, active.revision + 1); + assert_eq!(kernel.state.lens_weights, active_weights); + + // An Active patch is handed no weights, so it cannot resolve any. + let resolved = patch::resolve_patch( + &kernel.state, + CommandId::new(), + &operations_patch(&kernel), + None, + None, + ) + .expect("resolves"); + assert!(resolved.lens_weights.is_none(), "an Active patch resolved lens weights"); + let after_patch = kernel.snapshot().unwrap(); + let patch = operations_patch(&kernel); + submit_owner( + &mut kernel, + &after_patch, + CommandBody::AdmitPatch { + answers: None, + patch, + }, + ); + assert_eq!(kernel.state.lens_weights, active_weights); + + // Every caller but the owner, with real weights. + let proposed = super::tests::stock_weights(); + let before = kernel.state.clone(); + for caller in [ + CallerId::Principal(human_principal()), + CallerId::Principal(PrincipalId::new("stranger@example.test")), + elaborator(JurisdictionKey::Uncovered), + CallerId::System(SystemCapability::Clock), + CallerId::System(SystemCapability::Consumer { + consumer: ConsumerId::of_name("lens-consumer"), + }), + ] { + let result = submit_as( + &mut kernel, + caller.clone(), + CommandBody::SetLensWeights { + weights: proposed.clone(), + }, + ); + assert!( + matches!(result, Err(KernelError::Unauthorized)), + "{caller:?} replaced the lens weights: {result:?}" + ); + } + assert_eq!(kernel.state, before); + + // The owner, with every lens named at zero. + let result = submit_as( + &mut kernel, + CallerId::Principal(owner()), + CommandBody::SetLensWeights { + weights: every_lens_at_zero(), + }, + ); + let Err(KernelError::PatchRejected(mismatches)) = result else { + panic!("a lens set that never draws was admitted: {result:?}"); + }; + assert_eq!(mismatches, vec![Mismatch::LensWeightsNeverDraw]); + assert_eq!(kernel.state, before); + + // The owner, with valid weights, against the revision before the + // last commit. + let stale = command( + &draft, + CommandId::new(), + CallerId::Principal(owner()), + CommandBody::SetLensWeights { + weights: proposed.clone(), + }, + ); + assert!(matches!( + kernel.submit(stale, &auth_principal(owner())), + Err(KernelError::RevisionMismatch { .. }) + )); + assert_eq!(kernel.state, before); + + // `apply_effect` re-decides: a hand-built effect under a non-owner or + // a system caller never applies, and neither does one that never draws. + for (caller, weights) in [ + (CallerId::Principal(human_principal()), proposed.clone()), + (CallerId::System(SystemCapability::Clock), proposed.clone()), + (CallerId::Principal(owner()), every_lens_at_zero()), + ] { + let mut candidate = kernel.state.clone(); + let error = apply_effect( + &mut candidate, + CommandId::new(), + &caller, + &WorldEffect::LensWeightsReplaced { weights }, + ) + .unwrap_err(); + assert!( + matches!( + error, + KernelError::Invariant(_) | KernelError::Unauthorized + ), + "{caller:?}: {error:?}" + ); + assert_eq!(candidate, kernel.state); + } + // The honest effect applies through the same arm. + let mut candidate = kernel.state.clone(); + apply_effect( + &mut candidate, + CommandId::new(), + &CallerId::Principal(owner()), + &WorldEffect::LensWeightsReplaced { + weights: proposed.clone(), + }, + ) + .expect("the owner's effect applies"); + assert_eq!(candidate.lens_weights, proposed); + + // Identical weights from the owner change nothing canonical: refused + // as `NoCanonicalChange`, and nothing commits. + let result = submit_as( + &mut kernel, + CallerId::Principal(owner()), + CommandBody::SetLensWeights { + weights: active_weights.clone(), + }, + ); + let Err(KernelError::PatchRejected(mismatches)) = result else { + panic!("identical lens weights were admitted: {result:?}"); + }; + assert_eq!(mismatches, vec![Mismatch::NoCanonicalChange]); + assert_eq!(kernel.state, before); + + // The order is admission, then effect. Identical weights from a + // non-owner are `Unauthorized`; and against a state whose own set + // never draws (no store holds one, so the state is built by hand), an + // identical all-zero set is `LensWeightsNeverDraw`, not a no-op. + let result = submit_as( + &mut kernel, + CallerId::Principal(human_principal()), + CommandBody::SetLensWeights { + weights: active_weights.clone(), + }, + ); + assert!( + matches!(result, Err(KernelError::Unauthorized)), + "a non-owner's identical set: {result:?}" + ); + assert_eq!(kernel.state, before); + let mut never = kernel.state.clone(); + never.lens_weights = every_lens_at_zero(); + let current = kernel.snapshot().unwrap(); + let identical_zero = command( + ¤t, + CommandId::new(), + CallerId::Principal(owner()), + CommandBody::SetLensWeights { + weights: every_lens_at_zero(), + }, + ); + let result = reduce(&never, &identical_zero); + let Err(KernelError::PatchRejected(mismatches)) = result else { + panic!("an identical set that never draws: {result:?}"); + }; + assert_eq!(mismatches, vec![Mismatch::LensWeightsNeverDraw]); + + // Replay across that history is unchanged: the refused attempts wrote + // nothing, and the store reopens to the same head. + let (path, world_id) = (directory.path().join("world.cc"), kernel.state.world_id); + drop(kernel); + let reopened = WorldKernel::open(path, world_id).expect("the history reopens"); + assert_eq!(reopened.state, before); + } + + /// An owner commit that adds a commitment to the first person: a real + /// Active patch with no answer, and nothing to do with lenses. + fn operations_patch(kernel: &WorldKernel) -> WorldPatch { + let subject = kernel + .state + .subjects + .iter() + .find(|(_, state)| state.kind == SubjectKind::Person) + .map(|(id, _)| *id) + .expect("a person"); + let CommandBody::AdmitPatch { patch, .. } = operations(vec![ComponentOp::CreateCommitment { + subject: Ref::Existing(subject), + counterparty: None, + kind: CommitmentKind::Goal, + due: FictionalMinutes(kernel.state.now.0 + 500), + period: None, + checks: Vec::new(), + statement: Statement::new("A promise kept with no flavor at all.").unwrap(), + }]) else { + panic!("the operations helper builds an admitted patch"); + }; + patch + } + + #[test] + fn lens_weights_enter_the_state_digest_and_no_scope_digest() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, _) = WorldKernel::create( + directory.path().join("world.cc"), + creation(CommandId::new(), "Digest Flavor"), + &auth_principal(owner()), + ) + .unwrap(); + let active = activate(&mut kernel); + + let mut other = kernel.state.clone(); + other.lens_weights = + LensWeights::new(BTreeMap::from([(Lens::Patina, 1), (Lens::Veil, 7)])); + assert_ne!( + state_digest(&other).unwrap(), + state_digest(&kernel.state).unwrap(), + "lens weights did not enter the state digest" + ); + + let digests = |kernel: &WorldKernel| -> BTreeMap { + derive_opportunities(&kernel.state) + .unwrap() + .into_iter() + .map(|opportunity| (opportunity.scope.subject_id, opportunity.scope_digest)) + .collect() + }; + let before = digests(&kernel); + assert!(!before.is_empty(), "the active fixture derives opportunities"); + submit_owner( + &mut kernel, + &active, + CommandBody::SetLensWeights { + weights: other.lens_weights.clone(), + }, + ); + assert_ne!(kernel.state.state_digest, active.state_digest); + assert_eq!(digests(&kernel), before, "lens weights entered a scope digest"); + } + + /// Soul falsification: a discharge names one subject's own live key. + #[test] + fn soul_discharging_a_foreign_or_already_discharged_commitment_is_refused() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Discharge"); + + // The farmer's obligation, claimed by the reeve. + let snapshot = kernel.snapshot().unwrap(); + assert_eq!( + reject_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::DischargeCommitment { + subject: Ref::Existing(clockwork.reeve), + key: clockwork.obligation, + }]), + ), + vec![Mismatch::UnknownCommitment { operation: 0 }] + ); + + // Discharged once, and then not again. + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::DischargeCommitment { + subject: Ref::Existing(clockwork.farmer), + key: clockwork.obligation, + }]), + ); + let snapshot = kernel.snapshot().unwrap(); + assert_eq!( + reject_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::DischargeCommitment { + subject: Ref::Existing(clockwork.farmer), + key: clockwork.obligation, + }]), + ), + vec![Mismatch::UnknownCommitment { operation: 0 }] + ); + } + + /// Soul falsification: a routine re-arms by exactly one period per command, + /// whatever the span, and a non-routine cannot carry checks. + #[test] + fn soul_a_routine_re_arms_exactly_one_period_per_command() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Rearm"); + let period = u64::from( + kernel.state.commitments[&clockwork.farmer][&clockwork.routine] + .period + .expect("a routine carries a period") + .minutes(), + ); + let start = due(&kernel, clockwork.farmer, clockwork.routine); + + // One roll per command, even for a span that clears many periods. + tick(&mut kernel, u32::try_from(period * 10).unwrap()).expect("the long tick commits"); + assert_eq!( + due(&kernel, clockwork.farmer, clockwork.routine), + FictionalMinutes(start.0 + period) + ); + tick(&mut kernel, 1).expect("the short tick commits"); + assert_eq!( + due(&kernel, clockwork.farmer, clockwork.routine), + FictionalMinutes(start.0 + 2 * period) + ); + + // Checks belong to routines alone. + let snapshot = kernel.snapshot().unwrap(); + assert_eq!( + reject_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::CreateCommitment { + subject: Ref::Existing(clockwork.reeve), + counterparty: None, + kind: CommitmentKind::Goal, + due: FictionalMinutes(100_000), + period: None, + checks: vec![PreconditionRef::Present { + at: Ref::Existing(clockwork.yard), + }], + statement: Statement::new("What was promised, as the promisor would say it.").unwrap(), + }]), + ), + vec![Mismatch::ChecksOnNonRoutine { operation: 0 }] + ); + } + + /// Soul falsification: `derive_motion` is a function of state and span + /// alone, and the committed effect is exactly what `reduce` re-derives for + /// a tick that fulfils a routine, presses past-due promises, and presses a + /// failing dependency at once. + #[test] + fn soul_derive_motion_is_pure_and_the_tick_replays_exactly() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Pure"); + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::CloseRoute { + route: Ref::Existing(clockwork.gate), + }]), + ); + + // The same state and the same span, twenty times: one answer. + let span = u32::try_from(LATE_DUE + 10).unwrap(); + let to = FictionalMinutes(LATE_DUE + 10); + let first = clock::derive_motion(&kernel.state, to); + assert!(!first.fulfilled.is_empty(), "the routine is due"); + assert!( + first.pressed.len() >= 2, + "past-due promises and the closed route all press" + ); + for _ in 0..20 { + assert_eq!(clock::derive_motion(&kernel.state, to), first); + } + + // And the commit carries exactly that motion. + let snapshot = kernel.snapshot().unwrap(); + let ticking = command( + &snapshot, + CommandId::new(), + clock_caller(), + CommandBody::AdvanceTime { + minutes: minutes(span), + }, + ); + let expected = reduce(&kernel.state, &ticking).expect("the tick reduces"); + assert_eq!( + expected, + WorldEffect::TimeAdvanced { + minutes: minutes(span), + to, + motion: first, + } + ); + // Applying the re-derived effect to a copy reproduces the committed + // state exactly, which is the replay identity the journal relies on. + let mut replayed = kernel.state.clone(); + apply_effect(&mut replayed, ticking.id, &clock_caller(), &expected) + .expect("the re-derived effect applies"); + kernel + .submit(ticking, &AuthenticatedCaller::fixture(clock_caller())) + .expect("the tick commits"); + assert_eq!(replayed.now, kernel.state.now); + assert_eq!(replayed.commitments, kernel.state.commitments); + assert_eq!(replayed.pressures, kernel.state.pressures); + } + + /// Soul falsification: a `BoundaryDigest` binds the structure that derives + /// it, and nothing else. The clock is not in the preimage, so a tick leaves + /// it where it is; closing the one route out of the dead end leaves the + /// predicate holding and must still move the digest. + #[test] + fn soul_a_boundary_digest_binds_its_structure_and_not_the_clock() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Digest"); + let destination = |kernel: &WorldKernel| { + derive_boundaries(&kernel.state) + .unwrap() + .into_iter() + .find_map(|boundary| match boundary { + CausalBoundary::UnelaboratedDestination { place, scope, .. } + if place == clockwork.dead_end => + { + Some(scope) + } + _ => None, + }) + .expect("the dead end") + }; + let before = destination(&kernel); + + // The clock moves; the digest does not. + tick(&mut kernel, 10).expect("the tick commits"); + assert_eq!(destination(&kernel), before, "the clock entered a preimage"); + + // The route's own record moves; the digest must follow. + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::CloseRoute { + route: Ref::Existing(clockwork.gate), + }]), + ); + assert_ne!( + destination(&kernel), + before, + "the digest ignored the route it names" + ); + } + + // ---- the elaborator capability ------------------------------------- + + fn elaborator(jurisdiction: JurisdictionKey) -> CallerId { + CallerId::System(SystemCapability::Elaborator { jurisdiction }) + } + + fn submit_as( + kernel: &mut WorldKernel, + caller: CallerId, + body: CommandBody, + ) -> Result { + let snapshot = kernel.snapshot().unwrap(); + kernel.submit( + command(&snapshot, CommandId::new(), caller.clone(), body), + &AuthenticatedCaller::fixture(caller), + ) + } + + fn dead_end_boundary(kernel: &WorldKernel) -> CausalBoundary { + derive_boundaries(&kernel.state) + .unwrap() + .into_iter() + .find(|boundary| matches!(boundary, CausalBoundary::UnelaboratedDestination { .. })) + .expect("the fixture derives one dead end") + } + + fn shed_under(container: EntityId, handle: &str) -> WorldPatch { + WorldPatch { + declarations: vec![Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(handle), + label: format!("The {handle}"), + kind: EntityKind::Place, + container: Some(Ref::Existing(container)), + })], + operations: Vec::new(), + evidence: Vec::new(), + } + } + + /// Verification 14: the mailbox port cannot express an unanswered + /// elaborator patch, so this is reachable only through the journal lane — + /// and it is refused there. + #[test] + fn elaborator_patch_without_answer_is_answer_required() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Unanswered"); + let revision = kernel.state.revision; + let error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CommandBody::AdmitPatch { + answers: None, + patch: shed_under(clockwork.dead_end, "shed"), + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::AnswerRequired), "{error:?}"); + assert_eq!(kernel.state.revision, revision); + } + + /// Verification 14: a jurisdiction whose every row is zero has nothing to + /// answer, so the answer is not derived. + #[test] + fn patch_answering_a_zero_deficit_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "ZeroDeficit"); + let jurisdiction = JurisdictionKey::PlaceSubtree(clockwork.dead_end); + assert!( + derive_scale_deficit(&kernel.state) + .unwrap() + .iter() + .all(|row| row.deficit == 0) + ); + let error = submit_as( + &mut kernel, + elaborator(jurisdiction), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Deficit(jurisdiction)), + patch: shed_under(clockwork.dead_end, "shed"), + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::AnswerNotDerived), "{error:?}"); + } + + /// The one admission rule at the top of `reduce` refuses four bodies before + /// any of them is read, and the clock's capability is refused the fifth. + #[test] + fn a_system_capability_is_admitted_for_exactly_one_body() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, active) = clock_kernel(directory.path(), "Capability"); + let held = elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)); + let opportunity = opportunity_for(&active, clockwork.reeve); + let answered = dead_end_boundary(&kernel); + let forbidden = [ + CommandBody::ApproveDraft, + CommandBody::ActivateWorld, + CommandBody::DeclineDecision { + opportunity: opportunity.clone(), + }, + CommandBody::AdvanceTime { + minutes: minutes(60), + }, + ]; + for body in forbidden { + let error = submit_as(&mut kernel, held.clone(), body).unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); + } + // The mirror: the clock may not author. + let error = submit_as( + &mut kernel, + clock_caller(), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered)), + patch: shed_under(clockwork.dead_end, "shed"), + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); + assert_eq!(kernel.state.revision, active.revision); + } + + /// Seed admission is the owner's lane: an elaborator in Draft has no + /// derived boundary to answer and nothing to be authorized for. + #[test] + fn elaborator_in_draft_is_unauthorized() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = WorldKernel::create( + directory.path().join("world.cc"), + creation(CommandId::new(), "DraftLane"), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let commons = kernel.snapshot().unwrap().places[0].id; + let error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(commons)), + CommandBody::AdmitPatch { + answers: None, + patch: shed_under(commons, "shed"), + }, + ) + .unwrap_err(); + // Draft answers nothing, so the answer gate passes and authority + // refuses: an elaborator with no answer holds nothing. + assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); + } + + /// Boundaries are covered transitively, so a parent jurisdiction's + /// elaborator may answer a boundary in a nested child — and a sibling root + /// may not answer it at all. + #[test] + fn boundary_jurisdiction_is_transitive_and_exclusive() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Transitive"); + let answered = dead_end_boundary(&kernel); + let hall = kernel.state.entities[&clockwork.yard] + .container + .expect("the yard sits in the hall"); + + // The hall's elaborator does not cover the unwalked road. + let error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(hall)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered.clone())), + patch: shed_under(clockwork.dead_end, "shed"), + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); + + // One unconfined owner patch answers that boundary and opens a second + // one strictly inside the hall, so the two coverings can be told apart + // on one world. + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered.clone())), + patch: WorldPatch { + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("shed"), + label: "The Roadside Shed".into(), + kind: EntityKind::Place, + container: Some(Ref::Existing(clockwork.dead_end)), + }), + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("cellar"), + label: "The Yard Cellar".into(), + kind: EntityKind::Place, + container: Some(Ref::Existing(clockwork.yard)), + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("hatch"), + label: "The Cellar Hatch".into(), + from: Ref::Existing(clockwork.yard), + to: Ref::Draft(DraftHandle::new("cellar")), + access: AccessKind::Public, + cost: Cost(1), + }), + ], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ); + assert!( + !derive_boundaries(&kernel.state) + .unwrap() + .contains(&answered) + ); + + let cellar = kernel + .state + .entities + .iter() + .find(|(_, entity)| entity.label == "The Yard Cellar") + .map(|(id, _)| *id) + .expect("the declared cellar"); + let nested = dead_end_boundary(&kernel); + assert!(matches!( + nested, + CausalBoundary::UnelaboratedDestination { place, .. } if place == cellar + )); + + // The road's root does not reach into the hall. + let error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(nested.clone())), + patch: shed_under(cellar, "crock"), + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); + + // The hall's does, transitively, through the same containment walk the + // civic lane uses. + submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(hall)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(nested.clone())), + patch: shed_under(cellar, "crock"), + }, + ) + .expect("the parent root covers a nested boundary"); + assert!(!derive_boundaries(&kernel.state).unwrap().contains(&nested)); + } + + /// A deficit is covered by exact key equality. A parent answering a child's + /// row would reduce two targets with one subject, because a subject under + /// nested roots counts toward both. + #[test] + fn parent_jurisdiction_cannot_answer_a_child_deficit_row() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = WorldKernel::create( + directory.path().join("world.cc"), + creation_with_intent( + CommandId::new(), + "Rows", + intent(super::tests::COMMONS, 3, 1000), + ), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let commons = *kernel + .state + .scale_intent + .jurisdictions + .keys() + .next() + .expect("the declared root"); + let active = activate(&mut kernel); + let inner = active.places[0].id; + let row = JurisdictionKey::PlaceSubtree(commons); + assert!( + derive_scale_deficit(&kernel.state) + .unwrap() + .iter() + .any(|candidate| candidate.jurisdiction == row && candidate.deficit > 0) + ); + let error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::Uncovered), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Deficit(row)), + patch: shed_under(inner, "shed"), + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); + } + + /// Confinement: a valid answer does not license a write outside the + /// jurisdiction, and a place with no container is a new root, which is the + /// owner's act. + #[test] + fn an_elaborator_cannot_write_outside_its_jurisdiction() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Confined"); + let answered = dead_end_boundary(&kernel); + let held = elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)); + + let foreign = submit_as( + &mut kernel, + held.clone(), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered.clone())), + patch: shed_under(clockwork.yard, "yardshed"), + }, + ) + .unwrap_err(); + assert!( + matches!(&foreign, KernelError::PatchRejected(set) + if set == &vec![Mismatch::OutsideJurisdiction { + site: Site::Declaration(DraftHandle::new("yardshed")), + }]), + "{foreign:?}" + ); + + let rootless = submit_as( + &mut kernel, + held, + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered.clone())), + patch: WorldPatch { + declarations: vec![Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("newroot"), + label: "A New Country".into(), + kind: EntityKind::Place, + container: None, + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ) + .unwrap_err(); + assert!( + matches!(&rootless, KernelError::PatchRejected(set) + if set == &vec![Mismatch::OutsideJurisdiction { + site: Site::Declaration(DraftHandle::new("newroot")), + }]), + "{rootless:?}" + ); + + // The owner is unconfined, and the identical rootless patch commits — + // once it answers something the kernel derives. + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered)), + patch: WorldPatch { + declarations: vec![Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("newroot"), + label: "A New Country".into(), + kind: EntityKind::Place, + container: Some(Ref::Existing(clockwork.dead_end)), + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ); + } + + /// Verification 17: seed admission and boundary elaboration reach one + /// reducer. The same structural defect returns the same complete set on + /// both lanes. + #[test] + fn seed_admission_and_boundary_elaboration_reach_one_reducer() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "OneReducer"); + let answered = dead_end_boundary(&kernel); + let dangling = |handle: &str| WorldPatch { + declarations: vec![Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(handle), + label: "The Nowhere Shed".into(), + kind: EntityKind::Place, + container: Some(Ref::Draft(DraftHandle::new("nothing"))), + })], + operations: Vec::new(), + evidence: Vec::new(), + }; + let snapshot = kernel.snapshot().unwrap(); + let owner_error = kernel + .submit( + command( + &snapshot, + CommandId::new(), + CallerId::Principal(owner()), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered.clone())), + patch: dangling("shed"), + }, + ), + &auth_principal(owner()), + ) + .unwrap_err(); + let elaborator_error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered.clone())), + patch: dangling("shed"), + }, + ) + .unwrap_err(); + let set_of = |error: &KernelError| match error { + KernelError::PatchRejected(set) => set.clone(), + other => panic!("{other:?}"), + }; + assert_eq!(set_of(&owner_error), set_of(&elaborator_error)); + + // And both lanes commit the sound patch through the one writer. + submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered)), + patch: shed_under(clockwork.dead_end, "shed"), + }, + ) + .expect("the elaborated patch commits"); + } + + /// `reduce` decides and `apply_effect` re-decides: a hand-built effect with + /// a jurisdiction that does not cover its answer never applies. + #[test] + fn apply_effect_re_decides_elaborator_authority() { + let directory = tempfile::tempdir().unwrap(); + let (kernel, clockwork, _) = clock_kernel(directory.path(), "Redecide"); + let answered = dead_end_boundary(&kernel); + let hall = kernel.state.entities[&clockwork.yard].container.unwrap(); + let command_id = CommandId::issue(); + let resolved = patch::resolve_patch( + &kernel.state, + command_id, + &shed_under(clockwork.dead_end, "shed"), + None, + None, + ) + .expect("the patch resolves"); + let effect = WorldEffect::PatchAdmitted { + answers: Some(PatchAnswer::Boundary(answered)), + resolved, + }; + + let mut candidate = kernel.state.clone(); + let error = apply_effect( + &mut candidate, + command_id, + &elaborator(JurisdictionKey::PlaceSubtree(hall)), + &effect, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_)), "{error:?}"); + assert_eq!(candidate, kernel.state); + + // The honest jurisdiction applies through the same arm. + let mut candidate = kernel.state.clone(); + apply_effect( + &mut candidate, + command_id, + &elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + &effect, + ) + .expect("the covering jurisdiction applies"); + assert_ne!(candidate, kernel.state); + } + + /// The mismatch vocabulary is kernel-internal plus controller telemetry. It + /// never enters a commit, and `verify_state_shape` never grows a clause for + /// it because no partition holds one. + #[test] + fn mismatch_never_appears_in_a_world_commit() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Separation"); + let answered = dead_end_boundary(&kernel); + submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered)), + patch: shed_under(clockwork.dead_end, "shed"), + }, + ) + .expect("the elaboration commits"); + + let bytes = rmp_serde::to_vec_named(&kernel.state).expect("state encodes"); + let text = String::from_utf8_lossy(&bytes); + for tag in [ + "outside_jurisdiction", + "unresolved_draft", + "no_canonical_change", + "mismatch", + ] { + assert!(!text.contains(tag), "{tag} reached world state"); + } + } + + // ---- Soul: the confinement predicate past its declaration lane ------ + + /// Confinement is claimed for every referent a jurisdictional author + /// writes, not only for declarations. An operation naming a route with one + /// endpoint outside the jurisdiction is outside, and the site it reports is + /// the operation's. + #[test] + fn soul_an_operation_naming_a_half_outside_route_is_outside_the_jurisdiction() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "OperationLane"); + let answered = dead_end_boundary(&kernel); + let revision = kernel.state.revision; + // The Field Gate runs hall -> dead end. The dead end's elaborator holds + // one of its two ends and therefore holds neither. + let mut patch = shed_under(clockwork.dead_end, "shed"); + patch.operations = vec![ComponentOp::AlterCost { + route: Ref::Existing(clockwork.gate), + cost: Cost(2), + }]; + let error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered.clone())), + patch, + }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set == &vec![Mismatch::OutsideJurisdiction { site: Site::Operation(0) }]), + "{error:?}" + ); + assert_eq!(kernel.state.revision, revision); + + // The owner is unconfined and the identical patch commits. + let snapshot = kernel.snapshot().unwrap(); + let mut owner_patch = shed_under(clockwork.dead_end, "shed"); + owner_patch.operations = vec![ComponentOp::AlterCost { + route: Ref::Existing(clockwork.gate), + cost: Cost(2), + }]; + submit_owner( + &mut kernel, + &snapshot, + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered)), + patch: owner_patch, + }, + ); + } + + /// The fifth body the capability rule refuses. `ExerciseDecision` is the + /// one the existing negative omits, and it is the one a subject's lane uses. + #[test] + fn soul_an_elaborator_cannot_exercise_a_decision() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, active) = clock_kernel(directory.path(), "NoExercise"); + let revision = kernel.state.revision; + let error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CommandBody::ExerciseDecision { + opportunity: opportunity_for(&active, clockwork.reeve), + invocation: DecisionInvocation { + affordance: clockwork.deliver, + bindings: Vec::new(), + proposed: Vec::new(), + speech: None, + display: None, + }, + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); + assert_eq!(kernel.state.revision, revision); + } + + /// Two boundaries under two disjoint roots, opened by one owner patch. + /// Answering one leaves the other derived with its digest unmoved, so the + /// second elaborator commits afterwards at a later revision. Answering the + /// first a second time is not derived. + #[test] + fn soul_disjoint_boundaries_commit_independently_and_a_spent_answer_is_not_derived() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Disjoint"); + let road = dead_end_boundary(&kernel); + let hall = kernel.state.entities[&clockwork.yard] + .container + .expect("the yard sits in the hall"); + + // One unconfined patch answers the road and opens one dead end under + // each root: a cellar under the yard, an annex off the road. + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(road)), + patch: WorldPatch { + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("cellar"), + label: "The Yard Cellar".into(), + kind: EntityKind::Place, + container: Some(Ref::Existing(clockwork.yard)), + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("hatch"), + label: "The Cellar Hatch".into(), + from: Ref::Existing(clockwork.yard), + to: Ref::Draft(DraftHandle::new("cellar")), + access: AccessKind::Public, + cost: Cost(1), + }), + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("annex"), + label: "The Road Annex".into(), + kind: EntityKind::Place, + container: Some(Ref::Existing(clockwork.dead_end)), + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("spur"), + label: "The Road Spur".into(), + from: Ref::Existing(clockwork.dead_end), + to: Ref::Draft(DraftHandle::new("annex")), + access: AccessKind::Public, + cost: Cost(1), + }), + ], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ); + + let place_named = |kernel: &WorldKernel, label: &str| { + kernel + .state + .entities + .iter() + .find(|(_, entity)| entity.label == label) + .map(|(id, _)| *id) + .expect("the declared place") + }; + let cellar = place_named(&kernel, "The Yard Cellar"); + let annex = place_named(&kernel, "The Road Annex"); + let boundary_at = |kernel: &WorldKernel, place: EntityId| { + derive_boundaries(&kernel.state) + .unwrap() + .into_iter() + .find(|boundary| { + matches!(boundary, CausalBoundary::UnelaboratedDestination { place: at, .. } if *at == place) + }) + .unwrap_or_else(|| panic!("no boundary at {place:?}")) + }; + // Both are derived at the same revision, and both are read before + // either is answered. + let cellar_answer = boundary_at(&kernel, cellar); + let annex_answer = boundary_at(&kernel, annex); + + submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(hall)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(cellar_answer.clone())), + patch: shed_under(cellar, "crock"), + }, + ) + .expect("the hall's elaborator answers the cellar"); + let after_first = kernel.state.revision; + + // The other root's answer is untouched by that commit: same value, + // same digest, still derived. + assert!( + derive_boundaries(&kernel.state) + .unwrap() + .contains(&annex_answer) + ); + submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(annex_answer)), + patch: shed_under(annex, "barrow"), + }, + ) + .expect("the road's elaborator answers the annex"); + assert!(kernel.state.revision > after_first); + + // The spent answer is a value nothing derives any more. + let error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(hall)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(cellar_answer)), + patch: shed_under(cellar, "second_crock"), + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::AnswerNotDerived), "{error:?}"); + } + + /// The third structural bound, reached through the elaborator lane: the + /// answer must be derived, every write must be inside the jurisdiction, and + /// the answer must stop being derived after the write. + #[test] + fn soul_an_elaborator_patch_that_does_not_satisfy_its_answer_is_refused() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Unsatisfied"); + let road = dead_end_boundary(&kernel); + let hall = kernel.state.entities[&clockwork.yard] + .container + .expect("the yard sits in the hall"); + + // One owner patch answers the road and opens a cellar dead end inside + // the hall, so the hall's elaborator has an answer it covers and a + // legal write that does not satisfy it. + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(road)), + patch: WorldPatch { + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("shed"), + label: "The Roadside Shed".into(), + kind: EntityKind::Place, + container: Some(Ref::Existing(clockwork.dead_end)), + }), + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("cellar"), + label: "The Yard Cellar".into(), + kind: EntityKind::Place, + container: Some(Ref::Existing(clockwork.yard)), + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("hatch"), + label: "The Cellar Hatch".into(), + from: Ref::Existing(clockwork.yard), + to: Ref::Draft(DraftHandle::new("cellar")), + access: AccessKind::Public, + cost: Cost(1), + }), + ], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ); + let cellar = kernel + .state + .entities + .iter() + .find(|(_, entity)| entity.label == "The Yard Cellar") + .map(|(id, _)| *id) + .expect("the declared cellar"); + let cellar_answer = derive_boundaries(&kernel.state) + .unwrap() + .into_iter() + .find(|boundary| { + matches!(boundary, CausalBoundary::UnelaboratedDestination { place, .. } if *place == cellar) + }) + .expect("the cellar is a dead end"); + let revision = kernel.state.revision; + + // Inside the hall, so confinement passes; nowhere near the cellar, so + // the answered boundary is still derived after the write. + let error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(hall)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(cellar_answer.clone())), + patch: shed_under(clockwork.yard, "yardshed"), + }, + ) + .unwrap_err(); + assert!( + matches!(error, KernelError::AnswerNotSatisfied), + "{error:?}" + ); + assert_eq!(kernel.state.revision, revision); + assert!( + derive_boundaries(&kernel.state) + .unwrap() + .contains(&cellar_answer), + "a refused patch left the boundary derived" + ); + + // The same author satisfying the same answer commits. + submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(hall)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(cellar_answer.clone())), + patch: shed_under(cellar, "crock"), + }, + ) + .expect("the satisfying patch commits"); + assert!( + !derive_boundaries(&kernel.state) + .unwrap() + .contains(&cellar_answer) + ); + } + + /// Pass 6's rule survives the ungating of `EvidenceRef::new`: a canonical + /// fact still needs its receipt listed on the patch that declares it, and an + /// elaborator gets the same refusal the owner does. + #[test] + fn soul_an_elaborator_cannot_mint_a_canonical_fact_without_a_listed_receipt() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "Provenance"); + let answered = dead_end_boundary(&kernel); + let revision = kernel.state.revision; + let mut patch = shed_under(clockwork.dead_end, "shed"); + patch.declarations.push(Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("flood"), + label: "The Flooded Hinge".into(), + statement: Statement::new("The lower hinge flooded.").expect("a canonical statement"), + standing: FactStandingRef::Canonical { + evidence: EvidenceRef::new("vault:forged"), + }, + })); + let error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered)), + patch, + }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::FactWithoutEvidence { + handle: DraftHandle::new("flood"), + })), + "{error:?}" + ); + assert_eq!(kernel.state.revision, revision); + } + + // ---- Cut 3: the play authority, `Ruled` facts and `Mint` ----------- + + fn play_caller() -> CallerId { + CallerId::System(SystemCapability::Play) + } + + fn ruled_fact_patch(handle: &str) -> WorldPatch { + WorldPatch { + declarations: vec![Declaration::Fact(FactDeclaration { + handle: DraftHandle::new(handle), + label: "The Ruling".into(), + statement: Statement::new("Stated by the table.").unwrap(), + standing: FactStandingRef::Ruled, + })], + operations: Vec::new(), + evidence: Vec::new(), + } + } + + fn resource_named(kernel: &WorldKernel, label: &str) -> EntityId { + *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == label) + .map(|(id, _)| id) + .expect("the declared resource") + } + + /// Invariant 5, first half, and P3.1: the play authority declares in + /// Active with no answer. + #[test] + fn the_play_authority_declares_in_active_without_an_answer() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PlayDeclares"); + let receipt = submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + answers: None, + patch: shed_under(clockwork.dead_end, "play-shed"), + }, + ) + .expect("the play authority declares unanswered in Active"); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + } + + /// Invariant 5, second half: the elaborator gate is unchanged. + #[test] + fn an_elaborator_declaration_in_active_without_an_answer_is_still_refused() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "ElaboratorUnanswered"); + let error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CommandBody::AdmitPatch { + answers: None, + patch: shed_under(clockwork.dead_end, "shed"), + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::AnswerRequired), "{error:?}"); + } + + /// Invariant 5, second half: the owner's own gate is unchanged too. Only + /// `Play` is exempted from `AnswerRequired`. + #[test] + fn the_owner_still_cannot_declare_unanswered_in_active() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "OwnerUnanswered"); + let snapshot = kernel.snapshot().unwrap(); + let error = kernel + .submit( + command( + &snapshot, + CommandId::new(), + CallerId::Principal(owner()), + CommandBody::AdmitPatch { + answers: None, + patch: shed_under(clockwork.dead_end, "shed"), + }, + ), + &auth_principal(owner()), + ) + .unwrap_err(); + assert!(matches!(error, KernelError::AnswerRequired), "{error:?}"); + } + + /// Invariant 5: the play authority reaches the whole world, unconfined to + /// a ground. Writing under a place no jurisdiction covers, with no + /// answer, is exactly what an elaborator or the owner cannot do. + #[test] + fn the_play_authority_is_unconfined() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PlayUnconfined"); + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + answers: None, + patch: shed_under(clockwork.dead_end, "unconfined-shed"), + }, + ) + .expect("the play authority is confined to no ground"); + } + + /// P3.6: the play authority cannot act in Draft. + #[test] + fn the_play_authority_is_refused_in_draft() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = WorldKernel::create( + directory.path().join("world.cc"), + creation(CommandId::new(), "PlayDraft"), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let commons = kernel.snapshot().unwrap().places[0].id; + let error = submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + answers: None, + patch: shed_under(commons, "shed"), + }, + ) + .unwrap_err(); + assert!( + matches!( + error, + KernelError::WrongPhase { + expected: WorldPhase::Active, + actual: WorldPhase::Draft, + } + ), + "{error:?}" + ); + } + + /// Invariant 5: the play authority advances time, the clock's precedent. + #[test] + fn the_play_authority_advances_time() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, _clockwork, active) = clock_kernel(directory.path(), "PlayClock"); + let receipt = submit_as( + &mut kernel, + play_caller(), + CommandBody::AdvanceTime { + minutes: minutes(30), + }, + ) + .expect("the play authority advances time"); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert!(kernel.state.now > active.now); + } + + /// P3.6: the play authority may not approve, activate, exercise, or + /// decline. `require_system_capability`, at the top of `reduce`, refuses + /// all four before any body-specific arm is read. + #[test] + fn the_play_authority_cannot_approve_activate_exercise_or_decline() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, active) = clock_kernel(directory.path(), "PlayForbidden"); + let opportunity = opportunity_for(&active, clockwork.reeve); + let forbidden = [ + CommandBody::ApproveDraft, + CommandBody::ActivateWorld, + CommandBody::ExerciseDecision { + opportunity: opportunity.clone(), + invocation: DecisionInvocation { + affordance: clockwork.deliver, + bindings: Vec::new(), + proposed: Vec::new(), + speech: None, + display: None, + }, + }, + CommandBody::DeclineDecision { + opportunity: opportunity.clone(), + }, + ]; + for body in &forbidden { + let error = submit_as(&mut kernel, play_caller(), body.clone()).unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized), "{error:?}"); + } + // The end-to-end check above cannot tell "refused before any + // body-specific arm is read" apart from a downstream refusal that + // would fail Play just as closed (`require_owner`, for one, refuses + // every non-owner caller regardless of what admitted it). Pin + // `require_system_capability` directly, so widening its table for + // `Play` is caught even though every arm behind it still happens to + // refuse `Play` on its own. + for body in &forbidden { + assert!( + matches!( + require_system_capability(&play_caller(), body), + Err(KernelError::Unauthorized) + ), + "require_system_capability admitted {body:?} for the play authority" + ); + } + } + + /// P3.4: a ruled fact is world truth to every subject that knows it. + #[test] + fn the_play_authority_rules_a_fact_and_a_witness_knows_it_as_canon() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PlayRules"); + let mut patch = ruled_fact_patch("verdict"); + patch.operations.push(ComponentOp::AcquireKnowledge { + subject: Ref::Existing(clockwork.reeve), + fact: Ref::Draft(DraftHandle::new("verdict")), + source: AuthoredSource::Witnessed, + confidence: Confidence::Certain, + }); + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + answers: None, + patch, + }, + ) + .expect("the play authority rules a fact and grants it as knowledge"); + + let fact = *kernel + .state + .facts + .iter() + .find(|(_, record)| record.statement.as_str() == "Stated by the table.") + .map(|(id, _)| id) + .expect("the ruled fact"); + assert_eq!(kernel.state.facts[&fact].standing, FactStanding::Ruled); + + let snapshot = kernel.snapshot().unwrap(); + let subject = snapshot + .subjects + .iter() + .find(|subject| subject.id == clockwork.reeve) + .expect("the reeve's snapshot"); + let known = subject + .knowledge + .iter() + .find(|held| held.fact == fact) + .expect("the reeve knows the ruled fact"); + assert_eq!(known.standing, FactStandingView::Canonical); + } + + /// P3.5: minted quantity balances the ledger, and replay reproduces it. + #[test] + fn the_play_authority_mints_and_the_ledger_balances() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (world_id, reeve, grain) = { + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PlayMints"); + let grain = resource_named(&kernel, "Winter Grain"); + let before = held(&kernel.state, clockwork.reeve, grain); + assert_eq!(before, 0); + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Mint { + holder: Ref::Existing(clockwork.reeve), + resource: Ref::Existing(grain), + qty: Quantity(7), + }], + evidence: Vec::new(), + }, + }, + ) + .expect("the play authority mints"); + let after = held(&kernel.state, clockwork.reeve, grain); + assert_eq!(before + 7, after); + (kernel.state.world_id, clockwork.reeve, grain) + }; + let replayed = WorldKernel::open(&path, world_id).expect("the minted store replays"); + assert_eq!(held(&replayed.state, reeve, grain), 7); + } + + /// The evidenced-knowledge clause is unchanged: a receipt cannot vouch for + /// an assertion the kernel never evaluated, and a `Ruled` fact is exactly + /// such an assertion. + #[test] + fn a_ruled_fact_cannot_be_known_evidenced() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PlayEvidenced"); + let mut patch = ruled_fact_patch("verdict"); + patch.operations.push(ComponentOp::AcquireKnowledge { + subject: Ref::Existing(clockwork.reeve), + fact: Ref::Draft(DraftHandle::new("verdict")), + source: AuthoredSource::Evidenced, + confidence: Confidence::Certain, + }); + let error = submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + answers: None, + patch, + }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::EvidencedKnowledgeOfClaim { operation: 0 })), + "{error:?}" + ); + } + + /// The evidence gate on `Canonical` facts and `Admit` is byte-for-byte the + /// same predicate at the same sites for every author, `Play` included + /// (P3.3). `Play` carries no receipts, so its `Admit` is refused like + /// anyone's without one. + #[test] + fn the_evidence_gate_is_unchanged_for_every_author() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PlayEvidenceGate"); + let grain = resource_named(&kernel, "Winter Grain"); + + // Without a receipt: `Play`'s `Admit` is refused exactly as anyone's. + let error = submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Admit { + holder: Ref::Existing(clockwork.reeve), + resource: Ref::Existing(grain), + qty: Quantity(1), + evidence: EvidenceRef::new("vault:uncited"), + }], + evidence: Vec::new(), + }, + }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::AdmitWithoutEvidence { operation: 0 })), + "{error:?}" + ); + + // With the receipt cited in the same patch, `Play`'s `Admit` is + // admitted like anyone unconfined's. + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Admit { + holder: Ref::Existing(clockwork.reeve), + resource: Ref::Existing(grain), + qty: Quantity(1), + evidence: EvidenceRef::new("vault:cited"), + }], + evidence: vec![EvidenceRef::new("vault:cited")], + }, + }, + ) + .expect("an evidenced admit is admitted for the play authority too"); + + // PA.f29a: the owner in Draft — the seed's caller. + { + let seed_directory = tempfile::tempdir().unwrap(); + let (mut seed_kernel, _) = WorldKernel::create( + seed_directory.path().join("world.cc"), + creation(CommandId::new(), "OwnerDraftEvidence"), + &auth_principal(owner()), + ) + .expect("a created world"); + let fact = |evidence: &str| { + Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("draft-fact"), + label: "The Draft Count".into(), + statement: Statement::new("The draft is counted.").unwrap(), + standing: FactStandingRef::Canonical { + evidence: EvidenceRef::new(evidence), + }, + }) + }; + let snapshot = seed_kernel.snapshot().unwrap(); + let uncited = seed_kernel + .submit( + command( + &snapshot, + CommandId::new(), + CallerId::Principal(owner()), + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![fact("vault:draft-uncited")], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ), + &auth_principal(owner()), + ) + .unwrap_err(); + assert!( + matches!(&uncited, KernelError::PatchRejected(set) + if set.contains(&Mismatch::FactWithoutEvidence { + handle: DraftHandle::new("draft-fact"), + })), + "{uncited:?}" + ); + let snapshot = seed_kernel.snapshot().unwrap(); + seed_kernel + .submit( + command( + &snapshot, + CommandId::new(), + CallerId::Principal(owner()), + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![fact("vault:draft-cited")], + operations: Vec::new(), + evidence: vec![EvidenceRef::new("vault:draft-cited")], + }, + }, + ), + &auth_principal(owner()), + ) + .expect("a cited canonical fact is admitted for the owner in Draft"); + } + + // PA.f29a: the owner in Active, with a real answer. Its own + // `clock_kernel`, so the boundary this answers is not the one the + // Play blocks above already left cleared. The cited patch also + // seats a fresh occupant at the dead end: what actually clears an + // `UnelaboratedDestination` boundary ("a commit clears exactly the + // boundary it answers"), so the citation succeeding is not + // masked by an `AnswerNotSatisfied` refusal. + { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "OwnerActiveEvidence"); + let answered = dead_end_boundary(&kernel); + let speak = super::tests::speak_entry(&kernel); + let fact = |evidence: &str| { + Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("active-fact"), + label: "The Active Count".into(), + statement: Statement::new("The active count stands.").unwrap(), + standing: FactStandingRef::Canonical { + evidence: EvidenceRef::new(evidence), + }, + }) + }; + let error = submit_as( + &mut kernel, + CallerId::Principal(owner()), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered.clone())), + patch: WorldPatch { + declarations: vec![fact("vault:active-uncited")], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::FactWithoutEvidence { + handle: DraftHandle::new("active-fact"), + })), + "{error:?}" + ); + submit_as( + &mut kernel, + CallerId::Principal(owner()), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered)), + patch: WorldPatch { + declarations: vec![ + fact("vault:active-cited"), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("wanderer"), + label: "The Owner's Wanderer".into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + affordances: BTreeSet::from([speak]), + position: Some(Ref::Existing(clockwork.dead_end)), + import_key: None, + }), + ], + operations: Vec::new(), + evidence: vec![EvidenceRef::new("vault:active-cited")], + }, + }, + ) + .expect("a cited canonical fact is admitted for the owner in Active"); + } + + // PA.f29a: an answered elaborator. Its own `clock_kernel` for the + // same reason. The occupant the cited patch seats at the dead end + // is inside the elaborator's own `PlaceSubtree` jurisdiction, so + // `confine_to_ground` admits it the same as the fact. + { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = + clock_kernel(directory.path(), "ElaboratorEvidence"); + let answered = dead_end_boundary(&kernel); + let speak = super::tests::speak_entry(&kernel); + let caller = elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)); + let fact = |evidence: &str| { + Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("elaborator-fact"), + label: "The Elaborator Count".into(), + statement: Statement::new("The elaborator count stands.").unwrap(), + standing: FactStandingRef::Canonical { + evidence: EvidenceRef::new(evidence), + }, + }) + }; + let error = submit_as( + &mut kernel, + caller.clone(), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered.clone())), + patch: WorldPatch { + declarations: vec![fact("vault:elaborator-uncited")], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::FactWithoutEvidence { + handle: DraftHandle::new("elaborator-fact"), + })), + "{error:?}" + ); + submit_as( + &mut kernel, + caller, + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered)), + patch: WorldPatch { + declarations: vec![ + fact("vault:elaborator-cited"), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("wanderer"), + label: "The Elaborator's Wanderer".into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + affordances: BTreeSet::from([speak]), + position: Some(Ref::Existing(clockwork.dead_end)), + import_key: None, + }), + ], + operations: Vec::new(), + evidence: vec![EvidenceRef::new("vault:elaborator-cited")], + }, + }, + ) + .expect("a cited canonical fact is admitted for an answered elaborator"); + } + + // PA.f29a: a consumer, on its own mirror. A consumer cannot canonize + // (confine_to_ground refuses `Canonical` for consumer ground + // outright), so this exercises the same gate through `Admit` + // instead. In Draft, where `require_answer` asks nothing of anyone, + // so this is the evidence gate alone and not entangled with a + // consumer's inability to ever clear a place-shaped boundary (a + // consumer touches no place at all). + { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = WorldKernel::create( + directory.path().join("world.cc"), + creation(CommandId::new(), "ConsumerMirrorEvidence"), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let commons = *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == "The Commons") + .expect("the declared commons") + .0; + let grain = { + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("grain"), + label: "Consumer Grain".into(), + kind: EntityKind::Resource, + container: None, + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ); + *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == "Consumer Grain") + .expect("the declared resource") + .0 + }; + let consumer_id = ConsumerId::of_name("clock-mirror-consumer"); + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("mirror"), + label: "The Clockwork Mirror".into(), + kind: SubjectKind::Institution, + controller: NewController::External { + consumer: consumer_id, + }, + affordances: BTreeSet::new(), + position: Some(Ref::Existing(commons)), + import_key: None, + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ); + let mirror = *kernel + .state + .subjects + .iter() + .find(|(_, subject)| subject.label == "The Clockwork Mirror") + .expect("the declared mirror") + .0; + let consumer_caller = CallerId::System(SystemCapability::Consumer { + consumer: consumer_id, + }); + + let error = submit_as( + &mut kernel, + consumer_caller.clone(), + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Admit { + holder: Ref::Existing(mirror), + resource: Ref::Existing(grain), + qty: Quantity(1), + evidence: EvidenceRef::new("vault:mirror-uncited"), + }], + evidence: Vec::new(), + }, + }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::AdmitWithoutEvidence { operation: 0 })), + "{error:?}" + ); + + submit_as( + &mut kernel, + consumer_caller, + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Admit { + holder: Ref::Existing(mirror), + resource: Ref::Existing(grain), + qty: Quantity(1), + evidence: EvidenceRef::new("vault:mirror-cited"), + }], + evidence: vec![EvidenceRef::new("vault:mirror-cited")], + }, + }, + ) + .expect("a cited admit is admitted for a consumer on its own mirror"); + } + } + + /// `reduce` decides and `apply_effect` re-decides: a forged + /// `PatchAdmitted` under an elaborator caller, carrying a `Mint` the + /// resolver would accept (the resolver is actor-blind) and that fully + /// satisfies confinement (the minted subject is declared inside the + /// elaborator's own jurisdiction), is still refused at apply. `Mint` + /// carries no confinement veto of its own — unlike a `Ruled` fact, + /// `confine_to_ground` has no redundant clause for it — so only + /// `require_ruler`'s re-decision can be refusing this. Follows + /// `apply_effect_re_decides_elaborator_authority`. + #[test] + fn apply_effect_re_decides_the_ruler() { + let directory = tempfile::tempdir().unwrap(); + let (kernel, clockwork, _) = clock_kernel(directory.path(), "RedecideRulerMint"); + let answered = dead_end_boundary(&kernel); + let speak = super::tests::speak_entry(&kernel); + let command_id = CommandId::issue(); + let patch = WorldPatch { + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("loot"), + label: "Roadside Loot".into(), + kind: EntityKind::Resource, + container: None, + }), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("finder"), + label: "The Roadside Finder".into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + affordances: BTreeSet::from([speak]), + position: Some(Ref::Existing(clockwork.dead_end)), + import_key: None, + }), + ], + operations: vec![ComponentOp::Mint { + holder: Ref::Draft(DraftHandle::new("finder")), + resource: Ref::Draft(DraftHandle::new("loot")), + qty: Quantity(4), + }], + evidence: Vec::new(), + }; + let resolved = patch::resolve_patch(&kernel.state, command_id, &patch, None, None) + .expect("the patch resolves; the resolver is actor-blind"); + let effect = WorldEffect::PatchAdmitted { + answers: Some(PatchAnswer::Boundary(answered)), + resolved, + }; + + let mut candidate = kernel.state.clone(); + let error = apply_effect( + &mut candidate, + command_id, + &elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + &effect, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_)), "{error:?}"); + assert_eq!(candidate, kernel.state); + + let mut candidate = kernel.state.clone(); + apply_effect(&mut candidate, command_id, &play_caller(), &effect) + .expect("the play authority applies through the same arm"); + assert_ne!(candidate, kernel.state); + } + + /// PA.f27a: the owner is a `CallerId::Principal` like any other, and + /// `apply_effect`'s re-decision of `require_ruler` carries no exemption + /// for that variant. A forged `PatchAdmitted` under the owner, carrying + /// a `Ruled` fact the resolver accepts (actor-blind) and that fully + /// satisfies confinement (the owner is unconfined), is still refused at + /// apply. Follows `apply_effect_re_decides_the_ruler`. + #[test] + fn apply_effect_re_decides_the_ruler_for_the_owner_too() { + let directory = tempfile::tempdir().unwrap(); + let (kernel, _, _) = clock_kernel(directory.path(), "RedecideRulerOwner"); + let answered = dead_end_boundary(&kernel); + let command_id = CommandId::issue(); + let patch = ruled_fact_patch("rule"); + let resolved = patch::resolve_patch(&kernel.state, command_id, &patch, None, None) + .expect("the patch resolves; the resolver is actor-blind"); + let effect = WorldEffect::PatchAdmitted { + answers: Some(PatchAnswer::Boundary(answered)), + resolved, + }; + + let mut candidate = kernel.state.clone(); + let error = apply_effect( + &mut candidate, + command_id, + &CallerId::Principal(owner()), + &effect, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_)), "{error:?}"); + assert_eq!(candidate, kernel.state); + } + + /// PA.f27b: `require_ruler` walks every operation, not only the first. + /// A harmless `Relocate` at index 0 followed by a `Mint` at index 1, + /// from a non-`Play` author, is refused at index 1. Kills a scan + /// narrowed to `.take(1)`. + #[test] + fn require_ruler_catches_a_mint_past_the_first_operation() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "RulerScansEveryOp"); + let grain = resource_named(&kernel, "Winter Grain"); + let stair = *kernel + .state + .edges + .iter() + .find(|(_, record)| record.label() == "The Yard Stair") + .expect("the declared route") + .0; + let snapshot = kernel.snapshot().unwrap(); + let Err(error) = kernel.submit( + command( + &snapshot, + CommandId::new(), + CallerId::Principal(owner()), + operations(vec![ + ComponentOp::Relocate { + subject: Ref::Existing(clockwork.reeve), + via: Ref::Existing(stair), + }, + ComponentOp::Mint { + holder: Ref::Existing(clockwork.reeve), + resource: Ref::Existing(grain), + qty: Quantity(4), + }, + ]), + ), + &auth_principal(owner()), + ) else { + panic!("a non-Play Mint past the first operation was admitted"); + }; + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::RuledWithoutAuthority { + site: patch::Site::Operation(1), + })), + "{error:?}" + ); + } + + /// PA.f27c: `require_ruler` reports every `Ruled` declaration, not only + /// the first. Two `Ruled` facts from a non-`Play` author are both + /// reported. Kills a check narrowed to the first ruled fact. + #[test] + fn require_ruler_reports_every_ruled_fact() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "RulerScansEveryFact"), + &auth_principal(owner()), + ) + .expect("a created world"); + let snapshot = kernel.snapshot().unwrap(); + let mut patch = ruled_fact_patch("first-rule"); + patch.declarations.push(Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("second-rule"), + label: "The Second Ruling".into(), + statement: Statement::new("Stated by the table, again.").unwrap(), + standing: FactStandingRef::Ruled, + })); + let Err(error) = kernel.submit( + command( + &snapshot, + CommandId::new(), + CallerId::Principal(owner()), + CommandBody::AdmitPatch { + answers: None, + patch, + }, + ), + &auth_principal(owner()), + ) else { + panic!("two non-Play Ruled facts were admitted"); + }; + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::RuledWithoutAuthority { + site: patch::Site::Declaration(DraftHandle::new("first-rule")), + }) && set.contains(&Mismatch::RuledWithoutAuthority { + site: patch::Site::Declaration(DraftHandle::new("second-rule")), + })), + "{error:?}" + ); + } + + /// P3.5, replay half, folded with a ruled fact: reopening the journal + /// reproduces both across the digest. + #[test] + fn a_journal_holding_a_ruled_fact_and_a_mint_replays() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (world_id, expected) = { + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PlayReplay"); + let grain = resource_named(&kernel, "Winter Grain"); + let mut patch = ruled_fact_patch("verdict"); + patch.operations.push(ComponentOp::Mint { + holder: Ref::Existing(clockwork.farmer), + resource: Ref::Existing(grain), + qty: Quantity(2), + }); + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + answers: None, + patch, + }, + ) + .expect("the play authority rules and mints in one patch"); + (kernel.state.world_id, kernel.snapshot().unwrap()) + }; + let replayed = WorldKernel::open(&path, world_id).expect("the store replays"); + assert_eq!(replayed.snapshot().unwrap(), expected); + drop(replayed); + let replayed_again = + WorldKernel::open(&path, world_id).expect("the store replays a second time"); + assert_eq!(replayed_again.snapshot().unwrap(), expected); + } + + // ---- Cut 4: retirement ------------------------------------------- + + fn retire_patch(subject: SubjectId) -> WorldPatch { + WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::Retire { + subject: Ref::Existing(subject), + }], + evidence: Vec::new(), + } + } + + /// The owner retires a subject in Active. `retire_patch` declares + /// nothing and cites no evidence, so `require_answer`'s `declares` gate + /// never opens for it and no answer is needed, exactly as an owner's + /// ordinary bare operation needs none. + fn owner_retires(kernel: &mut WorldKernel, subject: SubjectId) -> Result { + submit_as( + kernel, + CallerId::Principal(owner()), + CommandBody::AdmitPatch { + answers: None, + patch: retire_patch(subject), + }, + ) + } + + /// Declares a mirror bound to a consumer this test invents, at the yard, + /// via the owner in Active. Shared by the retirement and grant tests that + /// need a subject `mode()` already excludes. + fn declare_mirror(kernel: &mut WorldKernel, clockwork: &Clockwork, name: &str) -> SubjectId { + let answered = dead_end_boundary(kernel); + submit_as( + kernel, + CallerId::Principal(owner()), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered)), + patch: WorldPatch { + declarations: vec![Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("mirror"), + label: "The Bound Hold".into(), + kind: SubjectKind::Institution, + controller: NewController::External { + consumer: ConsumerId::of_name(name), + }, + affordances: BTreeSet::new(), + // At the dead end, so this declaration also clears + // the boundary its own answer claims: an occupied + // place is no longer unelaborated. + position: Some(Ref::Existing(clockwork.dead_end)), + import_key: None, + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }, + ) + .expect("the owner declares a mirror in Active"); + kernel + .snapshot() + .unwrap() + .subjects + .iter() + .find(|subject| subject.label == "The Bound Hold") + .expect("the declared mirror") + .id + } + + /// P4.1, replay half: reopening the journal reproduces a retirement — + /// no opportunity and `retired` both survive the round trip. + #[test] + fn a_retired_subject_holds_no_opportunity_across_a_replay() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (world_id, reeve) = { + let (mut kernel, clockwork, active) = clock_kernel(directory.path(), "RetireReplay"); + assert!( + active + .opportunities + .iter() + .any(|opportunity| opportunity.scope.subject_id == clockwork.reeve), + "the reeve holds an opportunity before retirement" + ); + owner_retires(&mut kernel, clockwork.reeve).expect("the owner retires the reeve"); + (kernel.state.world_id, clockwork.reeve) + }; + let replayed = WorldKernel::open(&path, world_id).expect("the store replays"); + let snapshot = replayed.snapshot().unwrap(); + assert!( + !snapshot + .opportunities + .iter() + .any(|opportunity| opportunity.scope.subject_id == reeve), + "a replayed retired subject holds no opportunity" + ); + let subject = snapshot + .subjects + .iter() + .find(|subject| subject.id == reeve) + .expect("the retired subject's own row"); + assert!(subject.retired); + } + + /// P4.1: a retired subject's last opportunity is stale, not honoured. + #[test] + fn a_retired_subject_cannot_act() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, active) = clock_kernel(directory.path(), "RetireCannotAct"); + let opportunity = opportunity_for(&active, clockwork.reeve); + owner_retires(&mut kernel, clockwork.reeve).expect("the owner retires the reeve"); + let error = submit_as( + &mut kernel, + CallerId::Controller(opportunity.controller_id), + CommandBody::DeclineDecision { opportunity }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::OpportunityMismatch), "{error:?}"); + } + + /// P4.1: no position, so a witness at the retired subject's former place + /// never reaches it, while a still-present subject at the same place + /// does. + #[test] + fn a_retired_subject_hears_nothing() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "RetireHearsNothing"); + owner_retires(&mut kernel, clockwork.reeve).expect("the owner retires the reeve"); + let mut patch = ruled_fact_patch("news"); + patch.operations.push(ComponentOp::Witness { + fact: Ref::Draft(DraftHandle::new("news")), + place: Ref::Existing(clockwork.yard), + confidence: Confidence::Certain, + }); + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + answers: None, + patch, + }, + ) + .expect("the play authority witnesses at the yard"); + let snapshot = kernel.snapshot().unwrap(); + let reeve = snapshot + .subjects + .iter() + .find(|subject| subject.id == clockwork.reeve) + .expect("the retired reeve's own row"); + assert!(reeve.knowledge.is_empty(), "{:?}", reeve.knowledge); + let farmer = snapshot + .subjects + .iter() + .find(|subject| subject.id == clockwork.farmer) + .expect("the farmer's own row"); + assert!(!farmer.knowledge.is_empty(), "the farmer still hears it"); + } + + /// P4.2: events, knowledge, holdings, and commitments all survive + /// retirement untouched. + #[test] + fn a_retired_subject_keeps_its_history() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "RetireKeepsHistory"); + let before_holdings = kernel.state.holdings.get(&clockwork.farmer).cloned(); + let before_commitments = kernel.state.commitments.get(&clockwork.farmer).cloned(); + assert!(before_holdings.is_some()); + assert!(before_commitments.is_some()); + owner_retires(&mut kernel, clockwork.farmer).expect("the owner retires the farmer"); + assert_eq!( + kernel.state.holdings.get(&clockwork.farmer).cloned(), + before_holdings + ); + assert_eq!( + kernel.state.commitments.get(&clockwork.farmer).cloned(), + before_commitments + ); + assert!(kernel.state.subjects.contains_key(&clockwork.farmer)); + } + + /// P4.1: retiring twice is `NoOperationEffect`, not a second retirement. + #[test] + fn retiring_twice_is_no_effect() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "RetireTwice"); + owner_retires(&mut kernel, clockwork.reeve).expect("the first retirement commits"); + let error = owner_retires(&mut kernel, clockwork.reeve).unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::NoOperationEffect { operation: 0 })), + "{error:?}" + ); + } + + /// P4.3: a mirror is owned by another world; this one cannot retire it. + #[test] + fn a_mirror_cannot_be_retired() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "RetireMirror"); + let mirror = declare_mirror(&mut kernel, &clockwork, "cut4-retire-mirror"); + let error = owner_retires(&mut kernel, mirror).unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::RetiresAMirror { operation: 0 })), + "{error:?}" + ); + } + + /// P4.3: `confine_to_ground` refuses a `Retire` for a confined author + /// unconditionally, even for a subject this same patch declares and + /// places inside the elaborator's own jurisdiction. + #[test] + fn an_elaborator_cannot_retire_inside_its_jurisdiction() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "RetireElaborator"); + let speak = super::tests::speak_entry(&kernel); + let answered = dead_end_boundary(&kernel); + let error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered)), + patch: WorldPatch { + declarations: vec![Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("stray"), + label: "The Roadside Stray".into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + affordances: BTreeSet::from([speak]), + position: Some(Ref::Existing(clockwork.dead_end)), + import_key: None, + })], + operations: vec![ComponentOp::Retire { + subject: Ref::Draft(DraftHandle::new("stray")), + }], + evidence: Vec::new(), + }, + }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::OutsideJurisdiction { + site: Site::Operation(0) + })), + "{error:?}" + ); + } + + /// P4.3: the owner and the play authority are the two callers a + /// `Retire` admits. + #[test] + fn the_owner_and_the_play_authority_may_retire() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "RetireOwnerAndPlay"); + owner_retires(&mut kernel, clockwork.reeve).expect("the owner retires the reeve"); + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + answers: None, + patch: retire_patch(clockwork.farmer), + }, + ) + .expect("the play authority retires the farmer"); + let snapshot = kernel.snapshot().unwrap(); + assert!( + snapshot + .subjects + .iter() + .find(|subject| subject.id == clockwork.reeve) + .unwrap() + .retired + ); + assert!( + snapshot + .subjects + .iter() + .find(|subject| subject.id == clockwork.farmer) + .unwrap() + .retired + ); + } + + // ---- Cut 5: granting and revoking affordances --------------------- + + fn wave_affordance() -> Declaration { + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("wave"), + kind: AffordanceKindName("wave".into()), + roles: vec![RoleSpec { + role: Role("target".into()), + kind: RefKind::Subject(None), + }], + preconditions: Vec::new(), + effect_slots: vec![EffectSlot { + op_kind: ComponentOpKind::AdvancePressure { + by: PressureMagnitude(1), + }, + roles: vec![Role("target".into())], + bounds: Bounds::None, + }], + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: vec![0], + }], + carries_speech: false, + }) + } + + /// P5.1: the seed lane is the owner in Draft, and it grants the player a + /// verb the same way any owner-authored `GrantAffordance` does. + #[test] + fn the_seed_grants_the_player_a_verb_in_draft() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = WorldKernel::create( + directory.path().join("world.cc"), + creation(CommandId::new(), "SeedGrantsDraft"), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let before = kernel.snapshot().unwrap(); + let commons = before.places[0].id; + let speak = super::tests::speak_entry(&kernel); + submit_owner( + &mut kernel, + &before, + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![ + wave_affordance(), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("player"), + label: "The Player".into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + affordances: BTreeSet::from([speak]), + position: Some(Ref::Existing(commons)), + import_key: None, + }), + ], + operations: vec![ComponentOp::GrantAffordance { + subject: Ref::Draft(DraftHandle::new("player")), + affordance: Ref::Draft(DraftHandle::new("wave")), + }], + evidence: Vec::new(), + }, + }, + ); + let snapshot = kernel.snapshot().unwrap(); + let player = snapshot + .subjects + .iter() + .find(|subject| subject.label == "The Player") + .expect("the declared player"); + assert_eq!(player.affordances.len(), 2); + } + + /// P5.1, and the scope digest half of Q10's design: a grant and a revoke + /// in Active both move the scope digest, so a stale opportunity is + /// `ScopeChanged` rather than silently honoured. + #[test] + fn the_play_authority_grants_and_revokes_in_active() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, active) = + clock_kernel(directory.path(), "PlayGrantRevoke"); + let stale = opportunity_for(&active, clockwork.reeve); + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![wave_affordance()], + operations: vec![ComponentOp::GrantAffordance { + subject: Ref::Existing(clockwork.reeve), + affordance: Ref::Draft(DraftHandle::new("wave")), + }], + evidence: Vec::new(), + }, + }, + ) + .expect("the play authority grants a new verb"); + let after_grant = kernel.snapshot().unwrap(); + assert_eq!( + after_grant + .subjects + .iter() + .find(|subject| subject.id == clockwork.reeve) + .unwrap() + .affordances + .len(), + 4 + ); + let error = submit_as( + &mut kernel, + CallerId::Controller(stale.controller_id), + CommandBody::DeclineDecision { + opportunity: stale.clone(), + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::ScopeChanged { .. }), "{error:?}"); + + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::RevokeAffordance { + subject: Ref::Existing(clockwork.reeve), + affordance: Ref::Existing(clockwork.threaten), + }], + evidence: Vec::new(), + }, + }, + ) + .expect("the play authority revokes a held verb"); + let after_revoke = kernel.snapshot().unwrap(); + let reeve = after_revoke + .subjects + .iter() + .find(|subject| subject.id == clockwork.reeve) + .unwrap(); + assert_eq!(reeve.affordances.len(), 3); + assert!(!reeve.affordances.contains(&clockwork.threaten)); + } + + /// P5.2: `derive_opportunities` requires at least one grant; a revoke + /// that would leave the reeve mute is refused before it ever reaches + /// that invariant. + #[test] + fn a_revoke_cannot_leave_a_subject_mute() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "RevokeMute"); + let speak = super::tests::speak_entry(&kernel); + for affordance in [clockwork.deliver, clockwork.threaten] { + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::RevokeAffordance { + subject: Ref::Existing(clockwork.reeve), + affordance: Ref::Existing(affordance), + }], + evidence: Vec::new(), + }, + }, + ) + .expect("the play authority revokes down toward one verb"); + } + let Ref::Existing(speak_id) = speak else { + panic!("speak is a standing affordance"); + }; + let error = submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::RevokeAffordance { + subject: Ref::Existing(clockwork.reeve), + affordance: Ref::Existing(speak_id), + }], + evidence: Vec::new(), + }, + }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::WouldLeaveSubjectMute { operation: 0 })), + "{error:?}" + ); + } + + /// PA.f30b: the last-verb refusal for `RevokeAffordance` (P5.2) holds for + /// a `Human`-controlled subject exactly as it does for any other + /// controller kind. Kills an exemption that only checks non-`Human` + /// subjects. + #[test] + fn a_revoke_cannot_leave_a_human_subject_mute() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, _, active) = clock_kernel(directory.path(), "RevokeHumanMute"); + let human = active + .subjects + .iter() + .find(|subject| subject.controller_mode == Some(ControllerMode::Human)) + .expect("the fixture world declares a human-controlled subject"); + let speak_affordance = *human + .affordances + .iter() + .next() + .expect("the human subject holds at least the kernel speak grant"); + let error = submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::RevokeAffordance { + subject: Ref::Existing(human.id), + affordance: Ref::Existing(speak_affordance), + }], + evidence: Vec::new(), + }, + }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::WouldLeaveSubjectMute { operation: 0 })), + "{error:?}" + ); + } + + /// PA.f30c: `ControllerAssignment::Retired.expected_caller()` is `None` + /// — a direct unit pin so an accidental `Some` for `Retired` is caught + /// here rather than only transitively through a submission test. + #[test] + fn retired_expects_no_caller() { + assert_eq!(ControllerAssignment::Retired.expected_caller(), None); + } + + /// P5.1: `confine_to_ground` refuses `GrantAffordance` for a confined + /// author unconditionally, even for a subject this same patch declares + /// and places inside the elaborator's own jurisdiction. + #[test] + fn an_elaborator_cannot_grant() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "GrantElaborator"); + let speak = super::tests::speak_entry(&kernel); + let answered = dead_end_boundary(&kernel); + let error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered)), + patch: WorldPatch { + declarations: vec![Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("stray"), + label: "The Roadside Stray".into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + affordances: BTreeSet::from([speak]), + position: Some(Ref::Existing(clockwork.dead_end)), + import_key: None, + })], + operations: vec![ComponentOp::GrantAffordance { + subject: Ref::Draft(DraftHandle::new("stray")), + affordance: Ref::Existing(clockwork.threaten), + }], + evidence: Vec::new(), + }, + }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::OutsideJurisdiction { + site: Site::Operation(0) + })), + "{error:?}" + ); + } + + // ---- Retirement fix batch (PA.f31-PA.f35) ------------------------------ + + fn human_subject(snapshot: &WorldSnapshot) -> SubjectId { + snapshot + .subjects + .iter() + .find(|subject| subject.controller_mode == Some(ControllerMode::Human)) + .expect("the genesis human") + .id + } + + /// PA.f31: `verify_state_shape` no longer judges a `DecisionEvent` against + /// the subject's *present* controller identity. Retiring a subject that + /// has acted commits, and the history survives a full reopen-and-replay + /// (`recover` -> `verify_history` -> `verify_state_shape` for every + /// commit, per the caller census in the report). + #[test] + fn retiring_a_subject_that_acted_survives_reopen_and_replay() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let world_id = { + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf31RetireActed"); + exercise( + &mut kernel, + clockwork.reeve, + clockwork.threaten, + vec![binding("target", Target::Subject(clockwork.farmer))], + ) + .expect("the threat commits"); + owner_retires(&mut kernel, clockwork.reeve) + .expect("a subject with history can be retired"); + kernel.state.world_id + }; + let reopened = WorldKernel::open(&path, world_id).expect("the store replays"); + let retired = reopened + .snapshot() + .unwrap() + .subjects + .iter() + .find(|subject| subject.label == "The Yard Reeve") + .expect("the reeve survives replay") + .retired; + assert!(retired); + } + + /// PA.f31: revoking a verb a subject has already used commits, and the + /// event that used it survives reopen-and-replay for the same reason: the + /// grant a `DecisionEvent` rode is judged once, at commit, not re-judged + /// against the present-day grant set. + #[test] + fn revoking_a_used_verb_survives_reopen_and_replay() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let world_id = { + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf31RevokeUsed"); + exercise( + &mut kernel, + clockwork.reeve, + clockwork.threaten, + vec![binding("target", Target::Subject(clockwork.farmer))], + ) + .expect("the threat commits"); + let before = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &before, + operations(vec![ComponentOp::RevokeAffordance { + subject: Ref::Existing(clockwork.reeve), + affordance: Ref::Existing(clockwork.threaten), + }]), + ); + kernel.state.world_id + }; + let reopened = WorldKernel::open(&path, world_id).expect("the store replays"); + assert_eq!(reopened.state.events.len(), 1); + } + + /// PA.f32(a): the resolver refuses `Retire` for a `Human`-controlled + /// subject while the world is Draft, before the owner can retire the + /// human, approve alone, and activate without the human's approval. + #[test] + fn retiring_the_human_in_draft_is_refused() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = WorldKernel::create( + directory.path().join("world.cc"), + creation(CommandId::new(), "PAf32DraftRefusal"), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let human = human_subject(&kernel.snapshot().unwrap()); + let error = owner_retires(&mut kernel, human).unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::RetiresAnApprover { operation: 0 })), + "{error:?}" + ); + } + + /// PA.f32(b, c): once the world is Active, the human's Draft approval is + /// frozen history, so the owner may retire the human — the player's + /// subject may die — and the retire survives reopen-and-replay because + /// the journal's approval-shape check no longer re-reads the present-day + /// controller roster in Active. + #[test] + fn retiring_the_human_in_active_survives_reopen_and_replay() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (world_id, human) = { + let (mut kernel, clockwork, active) = clock_kernel(directory.path(), "PAf32ActiveRetire"); + let _ = &clockwork; + let human = human_subject(&active); + owner_retires(&mut kernel, human).expect("the owner retires the human subject"); + (kernel.state.world_id, human) + }; + let reopened = WorldKernel::open(&path, world_id).expect("the store replays"); + let retired = reopened + .snapshot() + .unwrap() + .subjects + .iter() + .find(|subject| subject.id == human) + .expect("the human survives replay") + .retired; + assert!(retired); + } + + /// PA.f33: audience derivation (`audience()`) is the one owner of who a + /// channel reaches, so a channel may still *declare* a retired member, + /// but that member is filtered out at the one read site — it gains no + /// knowledge from a telling into that channel. + #[test] + fn channel_audience_excludes_a_retired_member() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf33Audience"); + owner_retires(&mut kernel, clockwork.reeve).expect("retire"); + let mut patch = ruled_fact_patch("news"); + patch.declarations.push(Declaration::Channel(ChannelDeclaration { + handle: DraftHandle::new("wire"), + label: "The Wire".into(), + reach: ReachRef::Subjects(BTreeSet::from([ + Ref::Existing(clockwork.reeve), + Ref::Existing(clockwork.farmer), + ])), + controller: None, + })); + patch.operations.push(ComponentOp::Communicate { + speaker: Ref::Existing(clockwork.farmer), + fact: Ref::Draft(DraftHandle::new("news")), + to: AudienceRef::Channel(Ref::Draft(DraftHandle::new("wire"))), + }); + submit_as(&mut kernel, play_caller(), CommandBody::AdmitPatch { answers: None, patch }) + .expect("admitted"); + let reeve_knows = kernel + .state + .knowledge + .get(&clockwork.reeve) + .map(BTreeMap::len) + .unwrap_or(0); + assert_eq!(reeve_knows, 0, "a retired subject was an audience"); + } + + /// PA.f33: `Communicate` resolves and refuses a retired speaker with + /// `RetiredSubjectActed`, whether or not it is also that channel's + /// controller. + #[test] + fn a_retired_subject_cannot_speak_through_a_channel() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf33RetiredSpeaks"); + let mut declare = ruled_fact_patch("wire-decl"); + declare.declarations.push(Declaration::Channel(ChannelDeclaration { + handle: DraftHandle::new("wire"), + label: "The Wire".into(), + reach: ReachRef::Subjects(BTreeSet::from([ + Ref::Existing(clockwork.reeve), + Ref::Existing(clockwork.farmer), + ])), + controller: None, + })); + submit_as(&mut kernel, play_caller(), CommandBody::AdmitPatch { answers: None, patch: declare }) + .expect("declare"); + owner_retires(&mut kernel, clockwork.reeve).expect("retire"); + let wire = *kernel.state.channels.keys().next().unwrap(); + let mut patch = ruled_fact_patch("news"); + patch.operations.push(ComponentOp::Communicate { + speaker: Ref::Existing(clockwork.reeve), + fact: Ref::Draft(DraftHandle::new("news")), + to: AudienceRef::Channel(Ref::Existing(wire)), + }); + let error = submit_as(&mut kernel, play_caller(), CommandBody::AdmitPatch { answers: None, patch }) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::RetiredSubjectActed { operation: 0 })), + "{error:?}" + ); + } + + /// PA.f33: `CanReach` is `audience().contains(target)`, so a retired + /// target fails the same precondition every other reach check now + /// respects — one statement of reach, one fix. + #[test] + fn a_retired_subject_is_unreachable_through_can_reach() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = WorldKernel::create( + directory.path().join("world.cc"), + creation(CommandId::new(), "PAf33CanReach"), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let (speech, _) = speech_world(&mut kernel); + owner_retires(&mut kernel, speech.listener).expect("the owner retires the listener"); + let snapshot = kernel.snapshot().unwrap(); + let opportunity = opportunity_for(&snapshot, speech.speaker); + let invocation = DecisionInvocation { + affordance: speech.whisper, + bindings: vec![binding("target", Target::Subject(speech.listener))], + proposed: Vec::new(), + speech: Some(Statement::new("Are you still there?").unwrap()), + display: None, + }; + let error = submit_as( + &mut kernel, + CallerId::Controller(opportunity.controller_id), + CommandBody::ExerciseDecision { invocation, opportunity }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::ActionRejected(set) + if set.contains(&ActionMismatch::CannotReach { precondition: 0 })), + "{error:?}" + ); + } + + /// PA.f34: `AcquireKnowledge` refuses a retired subject. + #[test] + fn a_retired_subject_cannot_acquire_knowledge() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf34Acquire"); + owner_retires(&mut kernel, clockwork.reeve).expect("retire"); + let mut patch = ruled_fact_patch("news"); + patch.operations.push(ComponentOp::AcquireKnowledge { + subject: Ref::Existing(clockwork.reeve), + fact: Ref::Draft(DraftHandle::new("news")), + source: AuthoredSource::Witnessed, + confidence: Confidence::Certain, + }); + let error = submit_as(&mut kernel, play_caller(), CommandBody::AdmitPatch { answers: None, patch }) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::RetiredSubjectActed { operation: 0 })), + "{error:?}" + ); + } + + /// PA.f34: `Forget` refuses a retired subject. + #[test] + fn a_retired_subject_cannot_forget() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf34Forget"); + let mut declare = ruled_fact_patch("news"); + declare.operations.push(ComponentOp::AcquireKnowledge { + subject: Ref::Existing(clockwork.reeve), + fact: Ref::Draft(DraftHandle::new("news")), + source: AuthoredSource::Witnessed, + confidence: Confidence::Certain, + }); + submit_as(&mut kernel, play_caller(), CommandBody::AdmitPatch { answers: None, patch: declare }) + .expect("the reeve learns the fact"); + let fact = *kernel.state.knowledge[&clockwork.reeve].keys().next().unwrap(); + owner_retires(&mut kernel, clockwork.reeve).expect("retire"); + let before = kernel.snapshot().unwrap(); + let error = reject_owner( + &mut kernel, + &before, + operations(vec![ComponentOp::Forget { + subject: Ref::Existing(clockwork.reeve), + fact: Ref::Existing(fact), + }]), + ); + assert_eq!(error, vec![Mismatch::RetiredSubjectActed { operation: 0 }]); + } + + /// PA.f34: `InstallIncumbent` refuses a retired subject as incumbent. + #[test] + fn a_retired_subject_cannot_take_office() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf34Office"); + owner_retires(&mut kernel, clockwork.farmer).expect("retire"); + let before = kernel.snapshot().unwrap(); + let error = reject_owner( + &mut kernel, + &before, + operations(vec![ + ComponentOp::OpenOffice { + institution: Ref::Existing(clockwork.treasury), + office: office("warden"), + delegated: BTreeSet::from([authority_kind("levy")]), + }, + ComponentOp::InstallIncumbent { + institution: Ref::Existing(clockwork.treasury), + office: office("warden"), + incumbent: Ref::Existing(clockwork.farmer), + }, + ]), + ); + assert_eq!(error, vec![Mismatch::RetiredSubjectActed { operation: 1 }]); + } + + /// PA.f34: a retired subject's holdings remain transferable — a body may + /// still be looted after it stops acting. + #[test] + fn holdings_are_still_transferable_from_a_retired_holder() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf34Loot"); + owner_retires(&mut kernel, clockwork.farmer).expect("retire"); + let before = kernel.snapshot().unwrap(); + let grain = *kernel + .state + .holdings + .get(&clockwork.farmer) + .expect("the retired farmer still holds grain") + .keys() + .next() + .expect("at least one resource"); + submit_owner( + &mut kernel, + &before, + operations(vec![ComponentOp::Transfer { + from: Ref::Existing(clockwork.farmer), + to: Ref::Existing(clockwork.reeve), + resource: Ref::Existing(grain), + qty: Quantity(2), + }]), + ); + assert_eq!( + kernel.state.holdings[&clockwork.reeve][&grain], + Quantity(2) + ); + } + + /// PA.f35, MuA: the resolver's `Retire` arm removes the subject's + /// Position (`positions.remove`) in the same candidate pass a later + /// `Relocate` in the same patch reads, so retire-then-relocate in one + /// patch is rejected as `UnplacedSubject` rather than silently placing a + /// retired subject. + #[test] + fn retiring_then_relocating_in_one_patch_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf35RetireRelocate"); + let stair = *kernel + .state + .edges + .iter() + .find(|(_, edge)| edge.endpoints().0 == clockwork.yard) + .unwrap() + .0; + let before = kernel.snapshot().unwrap(); + let error = reject_owner( + &mut kernel, + &before, + operations(vec![ + ComponentOp::Retire { subject: Ref::Existing(clockwork.reeve) }, + ComponentOp::Relocate { + subject: Ref::Existing(clockwork.reeve), + via: Ref::Existing(stair), + }, + ]), + ); + assert_eq!(error, vec![Mismatch::UnplacedSubject { operation: 1 }]); + } + + /// PA.f35, MuB: `RevokeAffordance` is confined exactly as every other + /// structural operation, so an elaborator cannot use it to touch a + /// subject's grants outside its jurisdiction. + #[test] + fn an_elaborator_cannot_revoke() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf35ElabRevoke"); + let answered = dead_end_boundary(&kernel); + let speak = super::tests::speak_entry(&kernel); + let error = submit_as( + &mut kernel, + elaborator(JurisdictionKey::PlaceSubtree(clockwork.dead_end)), + CommandBody::AdmitPatch { + answers: Some(PatchAnswer::Boundary(answered)), + patch: WorldPatch { + declarations: vec![Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("stray"), + label: "The Roadside Stray".into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + affordances: BTreeSet::from([ + speak.clone(), + Ref::Existing(clockwork.threaten), + ]), + position: Some(Ref::Existing(clockwork.dead_end)), + import_key: None, + })], + operations: vec![ComponentOp::RevokeAffordance { + subject: Ref::Draft(DraftHandle::new("stray")), + affordance: Ref::Existing(clockwork.threaten), + }], + evidence: Vec::new(), + }, + }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::OutsideJurisdiction { site: Site::Operation(0) })), + "{error:?}" + ); + } + + /// PA.f35, MuC: `retired` on a subject snapshot row is read from + /// `ControllerAssignment::Retired` specifically, not from + /// `mode().is_none()` — a mirror's mode is also `None`, and a mirror must + /// never be reported retired. + #[test] + fn a_mirror_is_not_reported_retired() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf35MirrorFlag"); + let mirror = declare_mirror(&mut kernel, &clockwork, "pa-f35-mirror"); + let snapshot = kernel.snapshot().unwrap(); + let row = snapshot.subjects.iter().find(|s| s.id == mirror).unwrap(); + assert!(!row.retired); + } + + /// PA.f35, MuD: the affordance-holdings candidate set is updated after + /// every grant and revoke in a patch, not only the first, so three + /// revokes in one patch still catch the one that would leave the subject + /// mute. + #[test] + fn three_revokes_in_one_patch_cannot_mute_the_subject() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf35ThreeRevokes"); + let speak = super::tests::speak_entry(&kernel); + let before = kernel.snapshot().unwrap(); + let error = reject_owner( + &mut kernel, + &before, + operations(vec![ + ComponentOp::RevokeAffordance { + subject: Ref::Existing(clockwork.reeve), + affordance: Ref::Existing(clockwork.threaten), + }, + ComponentOp::RevokeAffordance { + subject: Ref::Existing(clockwork.reeve), + affordance: Ref::Existing(clockwork.deliver), + }, + ComponentOp::RevokeAffordance { + subject: Ref::Existing(clockwork.reeve), + affordance: speak, + }, + ]), + ); + assert_eq!(error, vec![Mismatch::WouldLeaveSubjectMute { operation: 2 }]); + } + + /// PA.f35, MuE: the resolver's `Retire` arm inserts the subject into its + /// own-patch `retired` candidate set, so a second `Retire` of the same + /// subject in one patch is caught as a no-op rather than silently + /// re-resolving. + #[test] + fn retiring_the_same_subject_twice_in_one_patch_is_a_noop_the_second_time() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf35DoubleRetire"); + let before = kernel.snapshot().unwrap(); + let error = reject_owner( + &mut kernel, + &before, + operations(vec![ + ComponentOp::Retire { subject: Ref::Existing(clockwork.reeve) }, + ComponentOp::Retire { subject: Ref::Existing(clockwork.reeve) }, + ]), + ); + assert_eq!(error, vec![Mismatch::NoOperationEffect { operation: 1 }]); + } + + // ---- Retirement fix batch (PA.f36-PA.f38) ------------------------------ + + /// PA.f36: the resolver refuses a genesis patch that declares a + /// Human-controlled subject and retires it in the same patch. The + /// resolver's `humans` candidate set tracks a freshly declared human the + /// same way `mirrors` tracks a freshly declared mirror, so this is caught + /// before `open_owner` ever commits an empty `world.cc` for a human who + /// never approved anything. + #[test] + fn genesis_cannot_declare_and_retire_the_human_in_one_patch() { + let directory = tempfile::tempdir().unwrap(); + let mut genesis = creation(CommandId::new(), "PAf36GenesisRetire"); + genesis.patch.operations.push(ComponentOp::Retire { + subject: Ref::Draft(DraftHandle::new("human")), + }); + let Err(error) = WorldKernel::create( + directory.path().join("world.cc"), + genesis, + &auth_principal(owner()), + ) else { + panic!("genesis admitted a patch that declares and retires the human"); + }; + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::RetiresAnApprover { operation: 0 })), + "{error:?}" + ); + } + + /// PA.f36: pins the apply-time re-check directly, beside the resolver's + /// refusal above, since resolution is speculative and this arm is the + /// actual commit. If the resolver's `humans` tracking were ever disabled + /// or bypassed, this is the arm that must still refuse removing a Draft + /// approver. + #[test] + fn apply_refuses_removing_a_draft_approver_directly() { + let directory = tempfile::tempdir().unwrap(); + let kernel = WorldKernel::create( + directory.path().join("world.cc"), + creation(CommandId::new(), "PAf36ApplyArm"), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let human = human_subject(&kernel.snapshot().unwrap()); + let mut state = kernel.state.clone(); + let resolves_to = state.revision + 1; + assert!( + matches!( + apply_operation( + &mut state, + &ResolvedOp::Retire { subject: human }, + &[], + resolves_to + ) + .unwrap_err(), + KernelError::Invariant(message) + if message == "retire operation would remove a Draft approver" + ), + "the apply-time arm no longer refuses removing the Draft human" + ); + } + + /// PA.f37: a retired subject cannot become a promisor. `CreateCommitment` + /// refuses it with `RetiredSubjectActed`, the same mismatch a retired + /// office incumbent draws. + #[test] + fn a_retired_subject_cannot_be_a_promisor() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf37Promisor"); + owner_retires(&mut kernel, clockwork.farmer).expect("retire"); + let before = kernel.snapshot().unwrap(); + let error = reject_owner( + &mut kernel, + &before, + operations(vec![ComponentOp::CreateCommitment { + subject: Ref::Existing(clockwork.farmer), + counterparty: None, + kind: CommitmentKind::Obligation, + due: FictionalMinutes(LATE_DUE + 1), + period: None, + checks: Vec::new(), + statement: Statement::new("What was promised, as the promisor would say it.") + .unwrap(), + }]), + ); + assert_eq!(error, vec![Mismatch::RetiredSubjectActed { operation: 0 }]); + } + + /// PA.f37: once a subject is retired, the clock stops moving what it + /// holds — its routine no longer rolls and its obligation no longer + /// presses — while a live subject's goal and dependency still move on the + /// same tick. Nothing is discharged or deleted; the retired subject's + /// commitments stay on record, un-fulfilled and un-pressed, exactly as + /// they were the moment it retired. + #[test] + fn after_retirement_a_tick_moves_none_of_the_retired_subjects_commitments() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf37Frozen"); + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::CloseRoute { + route: Ref::Existing(clockwork.gate), + }]), + ); + owner_retires(&mut kernel, clockwork.farmer).expect("retire the farmer"); + let routine_before = due(&kernel, clockwork.farmer, clockwork.routine); + let dependency_source = PressureSource::Dependency(DependencyTarget::Route(clockwork.gate)); + + tick(&mut kernel, ROUTINE_DUE as u32 + LATE_DUE as u32).expect("the tick commits"); + + assert_eq!( + due(&kernel, clockwork.farmer, clockwork.routine), + routine_before, + "a retired subject's routine still rolled" + ); + assert_eq!( + pressure( + &kernel, + clockwork.farmer, + PressureSource::Commitment { + subject: clockwork.farmer, + key: clockwork.obligation, + } + ), + 0, + "a retired subject's obligation still pressed" + ); + assert_eq!( + pressure( + &kernel, + clockwork.reeve, + PressureSource::Commitment { + subject: clockwork.reeve, + key: clockwork.goal, + } + ), + 1, + "the live subject's goal did not press" + ); + assert_eq!( + pressure(&kernel, clockwork.reeve, dependency_source), + 1, + "the live subject's dependency did not press" + ); + + assert!( + kernel.state.commitments[&clockwork.farmer].contains_key(&clockwork.routine), + "the frozen routine was discharged or deleted rather than left as history" + ); + assert!( + kernel.state.commitments[&clockwork.farmer].contains_key(&clockwork.obligation), + "the frozen obligation was discharged or deleted rather than left as history" + ); + } + + /// PA.f37, the other half: retiring the subject that holds the goal and + /// the dependency freezes those instead, while the still-live farmer's + /// routine and obligation keep moving. Soul's probe retired a subject + /// whose routine rolled and whose goal and dependency kept pressing; this + /// pins the dependency loop in `derive_motion` the first test above never + /// exercises, since the farmer it retires holds no dependency. + #[test] + fn after_retirement_a_tick_moves_none_of_the_retired_subjects_goal_or_dependency() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf37FrozenDep"); + let snapshot = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &snapshot, + operations(vec![ComponentOp::CloseRoute { + route: Ref::Existing(clockwork.gate), + }]), + ); + owner_retires(&mut kernel, clockwork.reeve).expect("retire the reeve"); + let routine_before = due(&kernel, clockwork.farmer, clockwork.routine); + let dependency_source = PressureSource::Dependency(DependencyTarget::Route(clockwork.gate)); + + tick(&mut kernel, ROUTINE_DUE as u32 + LATE_DUE as u32).expect("the tick commits"); + + assert_eq!( + pressure( + &kernel, + clockwork.reeve, + PressureSource::Commitment { + subject: clockwork.reeve, + key: clockwork.goal, + } + ), + 0, + "a retired subject's goal still pressed" + ); + assert_eq!( + pressure(&kernel, clockwork.reeve, dependency_source), + 0, + "a retired subject's dependency still pressed" + ); + assert_ne!( + due(&kernel, clockwork.farmer, clockwork.routine), + routine_before, + "the live subject's routine did not roll" + ); + assert_eq!( + pressure( + &kernel, + clockwork.farmer, + PressureSource::Commitment { + subject: clockwork.farmer, + key: clockwork.obligation, + } + ), + 1, + "the live subject's obligation did not press" + ); + } + + /// PA.f37: the freeze survives a full reopen-and-replay, the same way + /// every other retirement effect in this batch does. + #[test] + fn a_retired_subjects_frozen_commitments_survive_reopen_and_replay() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (world_id, farmer, routine, obligation) = { + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf37Replay"); + owner_retires(&mut kernel, clockwork.farmer).expect("retire the farmer"); + tick(&mut kernel, ROUTINE_DUE as u32 + LATE_DUE as u32).expect("the tick commits"); + ( + kernel.state.world_id, + clockwork.farmer, + clockwork.routine, + clockwork.obligation, + ) + }; + let reopened = WorldKernel::open(&path, world_id).expect("the store replays"); + assert_eq!( + due(&reopened, farmer, routine), + FictionalMinutes(ROUTINE_DUE), + "the routine rolled somewhere along the replayed path" + ); + assert_eq!( + pressure( + &reopened, + farmer, + PressureSource::Commitment { + subject: farmer, + key: obligation, + } + ), + 0, + "the obligation pressed somewhere along the replayed path" + ); + } + + // ---- Retirement fix batch, test gaps (PA.f39) -------------------------- + + /// PA.f39, M2: `AcquireKnowledge` refuses a retired subject regardless of + /// source. `Evidenced` already carries its own provenance guard + /// (`EvidencedKnowledgeOfClaim`), which makes it plausible for a future + /// edit to narrow the retirement check to `source != Evidenced`; this + /// proves the retirement check still fires for an `Evidenced` acquire + /// too. + #[test] + fn a_retired_subject_cannot_acquire_evidenced_knowledge() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf39Evidenced"); + owner_retires(&mut kernel, clockwork.farmer).expect("retire"); + let patch = WorldPatch { + declarations: vec![Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("news"), + label: "The Harvest Report".into(), + statement: Statement::new("The winter grain is counted.").unwrap(), + standing: FactStandingRef::Canonical { + evidence: EvidenceRef::new("vault:count"), + }, + })], + operations: vec![ComponentOp::AcquireKnowledge { + subject: Ref::Existing(clockwork.farmer), + fact: Ref::Draft(DraftHandle::new("news")), + source: AuthoredSource::Evidenced, + confidence: Confidence::Certain, + }], + evidence: vec![EvidenceRef::new("vault:count")], + }; + let error = submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { answers: None, patch }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::PatchRejected(set) + if set.contains(&Mismatch::RetiredSubjectActed { operation: 0 })), + "{error:?}" + ); + } + + /// PA.f39, M6: `is_retired` reads `ControllerAssignment::Retired` + /// specifically. If it also matched `ExternallyControlled`, a mirror + /// would be silently dropped from `Reach::Subjects` audience derivation — + /// the same site PA.f33 fixed for an actually retired member. A mirror is + /// not retired, and stays in the audience. + #[test] + fn a_mirror_in_a_subjects_channel_stays_in_the_audience() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf39MirrorAudience"); + let mirror = declare_mirror(&mut kernel, &clockwork, "pa-f39-mirror"); + let mut patch = ruled_fact_patch("news"); + patch.declarations.push(Declaration::Channel(ChannelDeclaration { + handle: DraftHandle::new("wire"), + label: "The Wire".into(), + reach: ReachRef::Subjects(BTreeSet::from([ + Ref::Existing(mirror), + Ref::Existing(clockwork.farmer), + ])), + controller: None, + })); + patch.operations.push(ComponentOp::Communicate { + speaker: Ref::Existing(clockwork.farmer), + fact: Ref::Draft(DraftHandle::new("news")), + to: AudienceRef::Channel(Ref::Draft(DraftHandle::new("wire"))), + }); + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { answers: None, patch }, + ) + .expect("admitted"); + let mirror_knows = kernel + .state + .knowledge + .get(&mirror) + .map(BTreeMap::len) + .unwrap_or(0); + assert_eq!( + mirror_knows, 1, + "a mirror was excluded from a Subjects-reach audience" + ); + } + + /// PA.f39, Soul's probe S2: `CanReach` to a placeless target reachable + /// only through a `Reach::Subjects` channel — no co-location is possible + /// — is refused once the target retires. This exercises `audience()`'s + /// channel side, which PA.f33's Colocated-only `CanReach` test + /// (`a_retired_subject_is_unreachable_through_can_reach`) never reaches, + /// and kills a mutation that removes `audience()`'s retired filter. + #[test] + fn a_retired_placeless_subject_is_unreachable_through_a_subjects_channel() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, clockwork, _) = clock_kernel(directory.path(), "PAf39S2"); + let speak = super::tests::speak_entry(&kernel); + submit_as( + &mut kernel, + play_caller(), + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![ + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("outcast"), + label: "The Placeless Outcast".into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + affordances: BTreeSet::from([speak.clone()]), + position: None, + import_key: None, + }), + Declaration::Channel(ChannelDeclaration { + handle: DraftHandle::new("wire"), + label: "The Outcast Wire".into(), + reach: ReachRef::Subjects(BTreeSet::from([ + Ref::Draft(DraftHandle::new("outcast")), + Ref::Existing(clockwork.farmer), + ])), + controller: None, + }), + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("hail"), + kind: AffordanceKindName("hail".into()), + roles: vec![ + RoleSpec { + role: Role("target".into()), + kind: RefKind::Subject(None), + }, + RoleSpec { + role: Role("channel".into()), + kind: RefKind::Entity(EntityKind::Channel), + }, + ], + preconditions: vec![Precondition::CanReach { + subject: Role("target".into()), + via: AudienceSpec::Channel(Role("channel".into())), + }], + effect_slots: Vec::new(), + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + carries_speech: true, + }), + ], + operations: vec![ComponentOp::GrantAffordance { + subject: Ref::Existing(clockwork.farmer), + affordance: Ref::Draft(DraftHandle::new("hail")), + }], + evidence: Vec::new(), + }, + }, + ) + .expect("the play authority declares the placeless outcast and its channel"); + + let positions = kernel.state.positions.clone(); + let outcast = *kernel + .state + .subjects + .keys() + .find(|id| !positions.contains_key(id)) + .expect("the declared placeless outcast"); + let wire = *kernel.state.channels.keys().next().expect("the declared channel"); + let snapshot = kernel.snapshot().unwrap(); + let hail = affordance_named(&snapshot, "hail"); + let opportunity = opportunity_for(&snapshot, clockwork.farmer); + let invocation = DecisionInvocation { + affordance: hail, + bindings: vec![ + binding("target", Target::Subject(outcast)), + binding("channel", Target::Entity(wire)), + ], + proposed: Vec::new(), + speech: Some(Statement::new("Hail!").unwrap()), + display: None, + }; + submit_as( + &mut kernel, + CallerId::Controller(opportunity.controller_id), + CommandBody::ExerciseDecision { + invocation: invocation.clone(), + opportunity: opportunity.clone(), + }, + ) + .expect("the live outcast is reachable through the channel"); + + owner_retires(&mut kernel, outcast).expect("retire the outcast"); + let snapshot = kernel.snapshot().unwrap(); + let opportunity = opportunity_for(&snapshot, clockwork.farmer); + let error = submit_as( + &mut kernel, + CallerId::Controller(opportunity.controller_id), + CommandBody::ExerciseDecision { invocation, opportunity }, + ) + .unwrap_err(); + assert!( + matches!(&error, KernelError::ActionRejected(set) + if set.contains(&ActionMismatch::CannotReach { precondition: 0 })), + "{error:?}" + ); + } +} diff --git a/native/aetherlight/src/patch.rs b/native/aetherlight/src/patch.rs new file mode 100644 index 000000000..31485e2d6 --- /dev/null +++ b/native/aetherlight/src/patch.rs @@ -0,0 +1,7760 @@ +//! Closed-patch resolution: the one owner of draft handles, reference kinds, and +//! declaration-lane ID allocation. +//! +//! Only [`derive_id`] allocates a canonical ID, and it is called from exactly +//! two sites: [`resolve_patch`] here, and `action::exercise`, which mints one +//! referent per speech-carrying invocation — always a `Claimed` fact asserted by +//! the acting subject. +//! +//! A patch names structure two ways and no other way: an exact canonical ID that +//! already keys a partition, or a draft handle declared in the same patch. +//! Resolution accumulates the complete mismatch set first and allocates only +//! after that set is empty, so a rejected patch never mints an ID. + +use super::clock::{FictionalMinutes, TickMinutes}; +use super::tool_schema; +use super::grammar::GrammarRefusal; +use super::{ + AffordanceId, CommandId, ControllerAssignment, ControllerId, EdgeId, EntityId, LensWeights, + NewController, SubjectId, SubjectKind, SubjectState, WorldId, +}; +use codex_connector::CodexToolDefinition; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; +use std::collections::{BTreeMap, BTreeSet, btree_map::Entry}; +use unicode_properties::{GeneralCategory, UnicodeGeneralCategory}; +use uuid::Uuid; + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub enum EntityKind { + Place, + Resource, + Fact, + Channel, +} + +/// Exactly the edge kinds that have a record shape. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub enum EdgeKind { + Route, +} + +/// Traversal rule. A `Restricted` route names the authority kind that opens it: +/// the door names its own key, and the kernel reads neither the door nor the key +/// beyond comparing the name. [`route_admits`] is the sole statement of who gets +/// through, reached identically by `resolve_patch`'s `Relocate` arm and by +/// `Precondition::Reachable`'s edge admission. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "access", rename_all = "snake_case")] +pub(crate) enum AccessKind { + Public, + Restricted { requires: AuthorityKindName }, +} + +/// A world-declared authority name: canonical text, `[a-z][a-z0-9_]{0,47}`. The +/// kernel carries it, compares it for equality, and reads it no other way. A +/// closed enum here would make "conscript" or "audit" a kernel change and put a +/// world's political vocabulary in the reducer. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub(crate) struct AuthorityKindName(pub(crate) String); + +/// What an authority covers. Distinct from `DecisionScope`, which says *whose* +/// authority it is and stays one field. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "over", content = "id", rename_all = "snake_case")] +pub(crate) enum AuthorityTarget { + Subject(SubjectId), + /// That place and everything contained in it, by `EntityRecord.container`. + PlaceSubtree(EntityId), +} + +impl AuthorityTarget { + /// The referent this target names, so "does grant A cover grant B's ground" + /// is the one covering predicate rather than a second one. + pub(super) fn as_referent(self) -> super::Target { + match self { + Self::Subject(subject_id) => super::Target::Subject(subject_id), + Self::PlaceSubtree(entity_id) => super::Target::Entity(entity_id), + } + } +} + +/// The proposal-time twin of [`AuthorityTarget`], carrying references. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "over", content = "ref", rename_all = "snake_case")] +pub(crate) enum AuthorityTargetRef { + Subject(Ref), + PlaceSubtree(Ref), +} + +/// One jurisdiction: a kind and the ground it runs over. Ordered `(kind, over)` +/// so a subject's grant set has one canonical order. A jurisdiction is a set of +/// these, so revoking one place is not a restatement of the whole scope. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(deny_unknown_fields)] +pub(crate) struct AuthorityGrant { + pub(crate) kind: AuthorityKindName, + pub(crate) over: AuthorityTarget, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(deny_unknown_fields)] +pub(crate) struct AuthorityGrantRef { + pub(crate) kind: AuthorityKindName, + pub(crate) over: AuthorityTargetRef, +} + +/// Canonical text, scoped to its institution: the pair (institution, name) is +/// the identity, the same discipline a `Role` gets inside one affordance. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub(crate) struct OfficeName(pub(crate) String); + +/// A seat inside one institution. It carries no term and no selection method: +/// there is no clock, so nothing can expire, and a field nothing reads is a +/// decoration the next pass has to delete. `delegated` is the field that earns +/// its keep — `scope_components` reads it, `Authorized` resolves through it, and +/// the scope digest binds it. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct Office { + /// A person subject, or vacant. A vacancy is an ordinary state. + pub(crate) incumbent: Option, + /// Which of the institution's authority kinds this office lends its + /// incumbent. Non-empty: an office lending nothing is inert. + pub(crate) delegated: BTreeSet, +} + +/// World-declared canonical text, kernel-opaque, `[a-z][a-z0-9_]{0,47}`. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub(crate) struct GrievanceKindName(pub(crate) String); + +/// Where one kind of grievance goes, and who may bring it. One forum per +/// grievance kind, world-wide; per-jurisdiction forums would key this on +/// `(GrievanceKindName, AuthorityTarget)`, and that key has no consumer yet. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct Forum { + /// Any subject. A one-person magistrate is a legitimate forum, so the + /// kernel branches on `SubjectKind` here as it does everywhere else: not at + /// all. + pub(crate) forum: SubjectId, + /// Who may bring this grievance. It reuses `AuthorityTarget`'s type and its + /// covering predicate and is emphatically not stored in the `authority` + /// partition, so `RevokeAuthority` cannot strip standing. + pub(crate) standing: AuthorityTarget, +} + +/// Whole minutes: the kernel's only time unit, so route cost adds and compares +/// with no converter. The valid range is checked, not typed, so a bad cost joins +/// the complete mismatch set instead of failing deserialization. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub(crate) struct Cost(pub(crate) u32); + +/// One year of minutes; bounds path sums. +pub(super) const MAX_ROUTE_COST: u32 = 525_600; + +/// A conserved count. Unsigned because a holding can never be negative: a signed +/// type would make "owes 3 iron" representable and push the real check to runtime +/// anyway. Subtraction is `checked_sub` and its failure is `InsufficientCustody`; +/// addition is `checked_add` and its failure is `QuantityOverflow`. No saturating +/// arithmetic anywhere, because a silent clamp is a silent conservation break. +/// There is no maximum: nothing sums quantities across resources, so the honest +/// bound is the type's. There is no unit, because a unit is where prices enter. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub(crate) struct Quantity(pub(crate) u64); + +/// What a subject depends on. A dependency is a bare relation: no magnitude, no +/// kind beyond its target namespace, no clock, no cost. The variant selects the +/// resolver, so the target kind is carried by the type rather than checked after +/// the fact. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "target", content = "id", rename_all = "snake_case")] +pub(crate) enum DependencyTarget { + Resource(EntityId), + Route(EdgeId), + Subject(SubjectId), +} + +/// The proposal-time twin of [`DependencyTarget`], carrying references rather +/// than canonical IDs. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "target", content = "ref", rename_all = "snake_case")] +pub(crate) enum DependencyRef { + Resource(Ref), + Route(Ref), + Subject(Ref), +} + +/// Where a subject stands. One place, derived from nothing else. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(deny_unknown_fields)] +pub(crate) struct Position { + pub(crate) place: EntityId, +} + +/// Namespace plus declared kind of a draft handle. A reference states the kind it +/// expects; resolution refuses a handle that answers with another one. A subject +/// expectation carries `None` where the referring position constrains the +/// namespace but not the kind. +/// +/// It is one predicate serving three readers: the resolution index, `Mismatch`, +/// and an affordance's `RoleSpec`, which persists inside the catalog and so +/// requires the serde derives. `Affordance` names the catalog namespace, which +/// carries no components and can never be a role's target. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "namespace", content = "kind", rename_all = "snake_case")] +pub enum RefKind { + Subject(Option), + Entity(EntityKind), + Edge(EdgeKind), + Affordance, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub struct DraftHandle(String); + +impl DraftHandle { + pub(super) fn new(value: impl Into) -> Self { + Self(value.into()) + } +} + +/// A reference is an exact canonical ID or a handle resolved in the same patch. +/// There is no third form and no `From`. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "ref", content = "value", rename_all = "snake_case")] +pub enum Ref { + Existing(Id), + Draft(DraftHandle), +} + +/// A referent in any of the three referent namespaces, or in the catalog. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "namespace", content = "ref", rename_all = "snake_case")] +pub enum RefName { + Subject(Ref), + Entity(Ref), + Edge(Ref), + Affordance(Ref), +} + +/// A world-declared affordance name. Canonical text, `[a-z][a-z0-9_]{0,47}`, +/// because it becomes a generated tool name and a tool name must be stable, +/// unique, and safe. The kernel carries it and branches on it nowhere; that is +/// what keeps genre out of the reducer. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub struct AffordanceKindName(pub String); + +/// A named slot in one affordance, bound to a referent at invocation time. +/// Canonical text, `[a-z][a-z0-9_]{0,31}` — it becomes a tool parameter name. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub struct Role(pub(crate) String); + +/// What a role must be bound to. `RefKind` is reused rather than mirrored: it +/// already spells subject, entity kind, and edge kind, so the binding kind-check +/// and the declaration kind-check are one predicate. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(deny_unknown_fields)] +pub(crate) struct RoleSpec { + pub(crate) role: Role, + pub(crate) kind: RefKind, +} + +/// Committed world text: canonical, non-empty. The kernel stores it, hands it to +/// a projection, and reads it no other way. Nothing compares two `Statement`s: +/// no dedup, no interning, no contradiction check, no similarity. Two facts with +/// byte-identical statements are two facts. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub struct Statement(String); + +impl Statement { + pub fn new(value: impl Into) -> Option { + let value = value.into(); + is_canonical_text(&value).then_some(Self(value)) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// How a fact stands. Immutable after admission: there is no `SetStanding`. A +/// claim never becomes canon and canon never degrades to a claim, so nothing +/// ever has to decide which of two facts wins. A world in which a court rules on +/// a rumour declares a *new* `Canonical` fact; the rumour survives beside it, +/// which is what makes a later `Redress` reading possible at all. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "standing", rename_all = "snake_case")] +pub(crate) enum FactStanding { + /// Admitted with a receipt, through the same evidence gate `Admit` uses. + Canonical { evidence: EvidenceRef }, + /// Asserted by a subject. The kernel does not evaluate the assertion. + Claimed { by: SubjectId }, + /// Stated by the play table. The kernel does not evaluate it; only `Play` + /// may write it. + Ruled, +} + +/// The proposal-time twin of [`FactStanding`]. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "standing", rename_all = "snake_case")] +pub(crate) enum FactStandingRef { + Canonical { evidence: EvidenceRef }, + Claimed { by: Ref }, + Ruled, +} + +/// One `EntityKind::Fact` row's payload. Write-once: only declaration and +/// `AssertClaim` ever write `facts`. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct FactRecord { + pub(crate) statement: Statement, + pub(crate) standing: FactStanding, +} + +/// Where a channel carries. A place reach is the subtree, through the same +/// [`covers_place`] walk a `PlaceSubtree` jurisdiction uses. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "reach", content = "of", rename_all = "snake_case")] +pub(crate) enum Reach { + /// Exactly these subjects. May be empty: an empty reach is the named + /// silenced state, which is the outcome this component exists to hold. + Subjects(BTreeSet), + /// Everyone positioned at that place or anywhere inside it. + Place(EntityId), +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "reach", content = "of", rename_all = "snake_case")] +pub(crate) enum ReachRef { + Subjects(BTreeSet>), + Place(Ref), +} + +/// One `EntityKind::Channel` row's payload. It carries no latency: there is no +/// clock, so a latency field would be read by nothing and bound by nothing. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct ChannelRecord { + pub(crate) reach: Reach, + /// Who may speak on it besides those inside its reach, and whose scope + /// digest binds it. The horn belongs to the temple, not to whoever happens + /// to be within earshot of it. + pub(crate) controller: Option, +} + +/// Lived meaning a subject carries: values, a voice, memories, and reads of +/// other subjects. It constrains no precondition, so it is outside every scope +/// digest and cannot interrupt a bound turn; it enriches projection and never +/// substitutes for authority, custody, topology, or knowledge. Set whole, so a +/// subject holds one value at one revision. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct PersonaMaterial { + pub(crate) values: Vec, + pub(crate) voice: Statement, + pub(crate) memories: Vec, + /// One read per subject, in canonical order. + pub(crate) reads: BTreeMap, +} + +/// The proposal-time twin of a read: the subject by reference. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct PersonaReadRef { + pub(crate) subject: Ref, + pub(crate) statement: Statement, +} + +/// A small closed ordinal. Ordered ascending by declaration order, so derived +/// `Ord` *is* the semantics and `Knows { at_least }` is one `>=`. Three levels: +/// two cannot express "I heard it but I doubt it", which is the state deception +/// produces; four or more is a scale nothing in the vocabulary distinguishes. +/// There is no zero — forgetting is a removed key, exactly as `Quantity(0)` is +/// unstorable. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub(crate) enum Confidence { + Doubted, + Believed, + Certain, +} + +/// Three sources with named writers: `Witnessed` is written by +/// `AcquireKnowledge` and by `Witness`, `Evidenced` by `AcquireKnowledge`, and +/// `Told` only by `Communicate`. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "source", rename_all = "snake_case")] +pub(crate) enum KnowledgeSource { + Witnessed, + /// `via: None` is co-location. + Told { + by: SubjectId, + via: Option, + }, + /// A visible act of `by`, perceived in the same place. Written only by + /// `ResolvedOp::Display`, which the kernel alone lowers. + Seen { + by: SubjectId, + }, + Evidenced, +} + +/// What one subject holds of one fact. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct Knowledge { + pub(crate) confidence: Confidence, + pub(crate) source: KnowledgeSource, + /// The revision at which this subject acquired this row: witnessed, + /// told, shown, or seeded by an author. Written by every writer of this + /// map (PA.f44), so the Projector's recency marker can tell a row minted + /// with no `minted_at` — a patch, a seed, a ruled fact — from one the + /// subject already held before its last act. + pub(crate) acquired_at: u64, +} + +/// The source an author may write. `Told` is unrepresentable here: only +/// `Communicate` writes it, so no author can forge a teller. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "source", rename_all = "snake_case")] +pub(crate) enum AuthoredSource { + Witnessed, + Evidenced, +} + +/// Where a telling lands. `Colocated` is derived from `positions` at check and +/// at apply; it is never a stored channel, so no entity is minted per place and +/// no world must enumerate a village to let people talk in a room. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub(crate) enum Audience { + Colocated, + Channel(EntityId), +} + +impl Audience { + pub(super) fn channel(self) -> Option { + match self { + Self::Colocated => None, + Self::Channel(entity_id) => Some(entity_id), + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub(crate) enum AudienceRef { + Colocated, + Channel(Ref), +} + +/// The catalog form: a declared affordance names a role, the invoker binds a +/// channel to it, and `exercise` lowers this plus the bindings into the +/// canonical [`Audience`]. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub(crate) enum AudienceSpec { + Colocated, + Channel(Role), +} + +/// What a subject has promised. The kernel branches on this twice — the tick +/// behaves differently per kind and the scale count reads `Goal` — so it is a +/// closed enum rather than a world-declared name. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub(crate) enum CommitmentKind { + Routine, + Obligation, + Goal, +} + +/// Deterministic from the creating command and the operation's index within +/// that command's lowered operations. No `EdgeId`: nothing references a +/// commitment by identity, so a structural key is the whole answer. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(deny_unknown_fields)] +pub struct CommitmentKey { + pub(crate) command: CommandId, + pub(crate) index: u32, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct Commitment { + pub(crate) kind: CommitmentKind, + /// `None` is a promise to oneself: a personal `Goal`. A counterparty equal + /// to the subject is refused. + pub(crate) counterparty: Option, + /// Absolute. "Past due" is `due <= now`: one comparison, no countdown + /// fanned across the partition. + pub(crate) due: FictionalMinutes, + /// Required for `Routine` — that is what makes it recur — and forbidden + /// otherwise. On auto-fulfilment `due` rolls forward by this. + pub(crate) period: Option, + /// What must hold for a `Routine` to auto-fulfil. Role-free canonical + /// checks. Empty for `Obligation` and `Goal`. + pub(crate) checks: Vec, + /// What is promised, as the promisor would state it. Without it a promise + /// is a clock and a name, and on the road both parties invented the rest. + pub(crate) statement: Statement, +} + +/// Nonzero by construction; saturating in both directions. A separate newtype +/// from [`super::Magnitude`], which is an effect ceiling and shares nothing with +/// this but a word. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub(crate) struct PressureMagnitude(pub(crate) u32); + +/// Target-major, because every reader is: the attention order reads pressure +/// *on* a subject and the typed view shows pressure on self. Source-major has no +/// reader. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "from", content = "of", rename_all = "snake_case")] +pub(crate) enum PressureSource { + /// A past-due commitment. Carries the promisor and the structural key. + Commitment { + subject: SubjectId, + key: CommitmentKey, + }, + /// An unavailable dependency of the pressed subject. This is how a closed + /// route in one realm becomes a political problem in another without anyone + /// deciding that it should be. + Dependency(DependencyTarget), + /// Another subject, pressing directly through an affordance effect. + Subject(SubjectId), +} + +/// The proposal-time twin of [`PressureSource`]. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "from", content = "of", rename_all = "snake_case")] +pub(crate) enum PressureSourceRef { + Commitment { + subject: Ref, + key: CommitmentKey, + }, + Dependency(DependencyRef), + Subject(Ref), +} + +/// The role-free canonical twin of [`Precondition`]. A `Precondition` names +/// roles; a `BoundPrecondition` names referents, so a commitment's checks are +/// storable with no second binding path and one evaluator serves both the +/// invocation pipeline and the tick. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "precondition", rename_all = "snake_case")] +pub(crate) enum BoundPrecondition { + Present { + at: EntityId, + }, + Reachable { + to: EntityId, + within: Cost, + }, + Holds { + resource: EntityId, + at_least: Quantity, + }, + Authorized { + over: super::Target, + kind: AuthorityKindName, + }, + HasStanding { + grievance: GrievanceKindName, + }, + Knows { + fact: EntityId, + at_least: Confidence, + }, + CanBroadcast { + via: Audience, + }, + CanReach { + subject: SubjectId, + via: Audience, + }, + Committed { + to: SubjectId, + kind: CommitmentKind, + }, +} + +/// The proposal-time twin of [`BoundPrecondition`], carried by +/// `CreateCommitment` so a patch may name a check over structure it declares. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "precondition", rename_all = "snake_case")] +pub(crate) enum PreconditionRef { + Present { + at: Ref, + }, + Reachable { + to: Ref, + within: Cost, + }, + Holds { + resource: Ref, + at_least: Quantity, + }, + Authorized { + over: AuthorityTargetRef, + kind: AuthorityKindName, + }, + HasStanding { + grievance: GrievanceKindName, + }, + Knows { + fact: Ref, + at_least: Confidence, + }, + CanBroadcast { + via: AudienceRef, + }, + CanReach { + subject: Ref, + via: AudienceRef, + }, + Committed { + to: Ref, + kind: CommitmentKind, + }, +} + +/// The authored scale target: how many qualified subjects of each kind the +/// world means to hold, and how that target distributes over jurisdiction +/// roots. Written once by genesis and never mutated. Not a component of any +/// referent, so not a `Declaration` and not a partition. +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct WorldScaleIntent { + /// Target qualified subjects per kind, world-wide. + pub(crate) targets: BTreeMap, + /// Jurisdiction roots and their share, in permille. Weights distribute the + /// target and never raise it: the sum is checked `<= 1000`. + pub(crate) jurisdictions: BTreeMap, +} + +/// The genesis-lane twin: the intent names places the same patch declares, and +/// there is no other way to name them before they exist. +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct WorldScaleIntentRef { + pub(crate) targets: BTreeMap, + pub(crate) jurisdictions: BTreeMap, +} + +/// One counted region of the scale deficit. `Uncovered` is the residual: a +/// subject with no jurisdiction root covering it — standing nowhere, or +/// standing somewhere outside every declared root's subtree — is counted and +/// visible while reducing no target. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "jurisdiction", content = "root", rename_all = "snake_case")] +pub enum JurisdictionKey { + PlaceSubtree(EntityId), + Uncovered, +} + +/// What must already be true of committed state before an invocation is +/// admitted. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "precondition", rename_all = "snake_case")] +pub(crate) enum Precondition { + /// The acting subject's Position names the place bound to `at`. + Present { at: Role }, + /// A path exists from the actor's place to the place bound to `to`, over + /// open routes this subject may traverse, with summed cost at most `within`. + Reachable { to: Role, within: Cost }, + /// The acting subject's own holding of the resource bound to `resource` is + /// at least `at_least`. + Holds { resource: Role, at_least: Quantity }, + /// The acting subject's effective authority — its own grants plus what + /// every office it occupies lends — holds a grant of `kind` whose target + /// covers the referent bound to `over`. + Authorized { over: Role, kind: AuthorityKindName }, + /// A forum takes `grievance` and the acting subject is inside its standing. + HasStanding { grievance: GrievanceKindName }, + /// The acting subject holds the fact bound to `fact` at `at_least` or + /// better. + Knows { fact: Role, at_least: Confidence }, + /// The acting subject has an audience at all: it is positioned, for + /// co-location, or it is inside the bound channel's reach or is its + /// controller. + CanBroadcast { via: AudienceSpec }, + /// The referent bound to `subject` is inside that audience. Addressing does + /// not narrow the audience: a telling still lands on everyone in it. + CanReach { subject: Role, via: AudienceSpec }, + /// The acting subject holds a commitment of `kind` to the referent bound to + /// `to`. This is what lets a world author an affordance whose legitimacy is + /// a promise rather than a jurisdiction. + Committed { to: Role, kind: CommitmentKind }, +} + +/// Exactly the operations an affordance may propose. `Admit` is absent because +/// minting quantity requires an `EvidenceRef` and an invocation carries no +/// evidence list, so admitting it here would be a second creation path beside +/// the single evidenced one. `OpenOffice`, `CloseOffice`, `OpenForum`, and +/// `CloseForum` are absent because constituting an office or a forum has no +/// live in-play reader an affordance would serve; they stay patch-lane only. +/// +/// `Witness` is a slot and `Communicate` is not, because a witnessed event is +/// world-caused and names no speaker, while speech is the actor's own act and +/// reaches an invocation only through the kernel-owned `carries_speech` +/// lowering: a proposer that could `Communicate` would choose a speaker, and a +/// proposer that `Witness`es chooses only where. +/// +/// The four civic variants carry their payload on the variant rather than on +/// the slot or the invocation: an authority kind and an office name are not +/// referents, so they cannot be roles, and a proposer's only degree of freedom +/// stays magnitude. The world fixes the kind when it authors the entry. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "op", rename_all = "snake_case")] +pub(crate) enum ComponentOpKind { + Relocate, + OpenRoute, + CloseRoute, + AlterCost, + Transfer, + Transform, + Consume, + Bind, + Release, + GrantAuthority { + kind: AuthorityKindName, + }, + RevokeAuthority { + kind: AuthorityKindName, + }, + InstallIncumbent { + office: OfficeName, + }, + VacateOffice { + office: OfficeName, + }, + /// Source is fixed to `Witnessed`: only `Communicate` writes a teller, and + /// `Evidenced` needs a patch's evidence list, which an invocation has not. + AcquireKnowledge { + confidence: Confidence, + }, + /// A world-authored event with no speaker: a beacon, a bell, a blast. The + /// slot names a fact and a place, never a subject, so a proposer's only + /// degree of freedom is which declared place the entry binds. The source is + /// `Witnessed` by construction — `ComponentOp::Witness` has no field a + /// teller could enter — so this lowering cannot forge one however it is + /// bound. + Witness { + confidence: Confidence, + }, + Forget, + /// The kind, the horizon, and the period are fixed on the variant, so a + /// proposer's only degree of freedom stays magnitude. `due` is + /// `now + horizon`, computed by the kernel at lowering: an absolute due on + /// a catalog entry would be a fixed date the world outgrows. + CreateCommitment { + kind: CommitmentKind, + horizon: TickMinutes, + period: Option, + }, + /// The source is fixed to the acting subject, so it cannot be forged. A + /// world authoring `threaten`, `reassure`, or `forgive` needs these three. + AdvancePressure { + by: PressureMagnitude, + }, + ReducePressure { + by: PressureMagnitude, + }, + ResolvePressure, +} + +/// The referent shape of one operation: the single source of both the +/// declaration check and the lowering. +pub(super) enum RoleKindRule { + Exact(RefKind), + AnyDependencyTarget, + AnyAuthorityTarget, +} + +/// Which magnitude, if any, an operation carries. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum BoundsDimension { + None, + Quantity, + Cost, +} + +impl ComponentOpKind { + pub(super) fn arity(&self) -> Vec { + let subject = || RoleKindRule::Exact(ANY_SUBJECT); + let route = || RoleKindRule::Exact(ROUTE); + let resource = || RoleKindRule::Exact(RefKind::Entity(EntityKind::Resource)); + match self { + Self::Relocate => vec![subject(), route()], + Self::OpenRoute | Self::CloseRoute | Self::AlterCost => vec![route()], + Self::Transfer => vec![subject(), subject(), resource()], + Self::Transform => vec![subject(), resource(), resource()], + Self::Consume => vec![subject(), resource()], + Self::Bind | Self::Release => vec![subject(), RoleKindRule::AnyDependencyTarget], + Self::GrantAuthority { .. } | Self::RevokeAuthority { .. } => { + vec![subject(), RoleKindRule::AnyAuthorityTarget] + } + Self::InstallIncumbent { .. } => vec![subject(), subject()], + Self::VacateOffice { .. } => vec![subject()], + Self::AcquireKnowledge { .. } | Self::Forget => { + vec![subject(), RoleKindRule::Exact(FACT)] + } + Self::Witness { .. } => vec![RoleKindRule::Exact(FACT), RoleKindRule::Exact(PLACE)], + // Promisor and counterparty. A `Goal` slot is refused at admission + // with `GoalWithCounterparty`: a promise to oneself has no second + // referent to bind, so the action lane authors `Routine` and + // `Obligation` and the patch lane authors goals. + Self::CreateCommitment { .. } => vec![subject(), subject()], + Self::AdvancePressure { .. } | Self::ReducePressure { .. } | Self::ResolvePressure => { + vec![subject()] + } + } + } + + pub(super) fn dimension(&self) -> BoundsDimension { + match self { + Self::Transfer | Self::Transform | Self::Consume => BoundsDimension::Quantity, + Self::AlterCost => BoundsDimension::Cost, + _ => BoundsDimension::None, + } + } + + /// The civic names this variant carries, so one validator checks them all. + fn payload_names(&self) -> Vec<&str> { + match self { + Self::GrantAuthority { kind } | Self::RevokeAuthority { kind } => vec![&kind.0], + Self::InstallIncumbent { office } | Self::VacateOffice { office } => vec![&office.0], + _ => Vec::new(), + } + } +} + +/// Whether a declared role kind can serve a position governed by this rule. +pub(super) fn role_kind_fits(rule: &RoleKindRule, declared: RefKind) -> bool { + match rule { + RoleKindRule::Exact(RefKind::Subject(_)) => matches!(declared, RefKind::Subject(_)), + RoleKindRule::Exact(expected) => *expected == declared, + RoleKindRule::AnyDependencyTarget => matches!( + declared, + RefKind::Subject(_) | RefKind::Entity(EntityKind::Resource) | RefKind::Edge(_) + ), + RoleKindRule::AnyAuthorityTarget => { + matches!(declared, RefKind::Subject(_) | PLACE) + } + } +} + +/// The magnitude ceiling for one slot. A closed enum matched to the operation's +/// dimension rather than a struct of optional ceilings: an `Option` ceiling that +/// is `None` is not a ceiling, and a struct admits the nonsense of a cost +/// ceiling on a `Transfer`. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "bound", content = "max", rename_all = "snake_case")] +pub(crate) enum Bounds { + None, + Quantity(Quantity), + Cost(Cost), +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct EffectSlot { + pub(crate) op_kind: ComponentOpKind, + /// Positional: exactly the referents `op_kind` takes, in `arity()` order. + pub(crate) roles: Vec, + pub(crate) bounds: Bounds, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct OutcomeBand { + /// At least 1. A zero-weight band is a branch that can never be selected. + pub(crate) weight: u32, + /// Indices into `effect_slots`, strictly increasing. Empty is legal and is + /// how a world expresses "the attempt does nothing". + pub(crate) effects: Vec, +} + +/// One catalog entry: what an affordance *is*. Who may use it is +/// `affordance_grants` and nothing else, so an entry carries no audience. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct Affordance { + pub kind: AffordanceKindName, + /// Ordered, so the generated tool's parameters are stable across builds. + pub(crate) roles: Vec, + pub(crate) preconditions: Vec, + pub(crate) effect_slots: Vec, + pub(crate) outcome_bands: Vec, + /// Every invocation of this entry carries exactly one utterance. The + /// kernel's only behaviour is to record it in the event; any world may + /// declare a speaking affordance, so this is not a Speak special case. + pub(crate) carries_speech: bool, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct AffordanceDeclaration { + pub(crate) handle: DraftHandle, + pub(crate) kind: AffordanceKindName, + pub(crate) roles: Vec, + pub(crate) preconditions: Vec, + pub(crate) effect_slots: Vec, + pub(crate) outcome_bands: Vec, + pub(crate) carries_speech: bool, +} + +/// Where a failed check appeared. One way to say it, for declarations and +/// operations alike. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "site", content = "at", rename_all = "snake_case")] +pub enum Site { + Declaration(DraftHandle), + Operation(usize), +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub(crate) struct EvidenceRef(String); + +impl EvidenceRef { + /// The elaborator's evidence receipts are built here, and `Deserialize` + /// already mints one from any string, so this constructor gates nothing. + /// Canonical text is checked by the resolver, in the complete mismatch set. + pub(super) fn new(value: impl Into) -> Self { + Self(value.into()) + } + + pub(super) fn text(&self) -> &str { + &self.0 + } +} + +/// The Aetheria record a subject was imported from: the CultCache schema id and +/// the record key, compared exactly as two separate texts so no pair of +/// distinct records can spell one key. Admission keeps the mapping injective; +/// a key is never matched by prefix, case or normalisation. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(deny_unknown_fields)] +pub struct ImportKey { + schema: String, + record: String, +} + +/// The longest either part of an import key may be, in bytes. +const MAX_IMPORT_KEY_PART_BYTES: usize = 200; + +impl ImportKey { + pub fn new(schema: impl Into, record: impl Into) -> Self { + Self { + schema: schema.into(), + record: record.into(), + } + } + + pub fn schema(&self) -> &str { + &self.schema + } + + pub fn record(&self) -> &str { + &self.record + } + + /// The one predicate for an import key, called by the resolver and by the + /// load-time state gate alike. The record part is canonical free text: not + /// empty, at most 200 bytes, no leading, trailing or doubled space, already NFC + /// (refused, never normalised, so the kernel derives no second spelling), + /// no control or format character, and no whitespace but U+0020. The schema + /// part is a schema id: the same text with no space at all. + pub(super) fn is_canonical(&self) -> bool { + is_canonical_key_text(&self.record) + && is_canonical_key_text(&self.schema) + && !self.schema.contains(' ') + } +} + +fn is_canonical_key_text(part: &str) -> bool { + !part.is_empty() + && part.len() <= MAX_IMPORT_KEY_PART_BYTES + && !part.starts_with(' ') + && !part.ends_with(' ') + && !part.contains(" ") + && unicode_normalization::is_nfc(part) + && part.chars().all(|c| { + !c.is_control() + && c.general_category() != GeneralCategory::Format + && (c == ' ' || !c.is_whitespace()) + }) +} + +/// Why an import key cannot join a world: the resolver names these by draft +/// handle, the state gates by invariant text. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum ImportKeyFault { + Malformed, + Held, + Duplicate, +} + +/// The keys the subjects hold, retired ones included, so a key is never +/// reissued. Derived on demand; no stored index. +pub(super) fn held_import_keys<'a>( + subjects: impl IntoIterator, +) -> BTreeSet<&'a ImportKey> { + subjects + .into_iter() + .filter_map(|subject| subject.import_key.as_ref()) + .collect() +} + +/// The one decision on a key: malformed, held by a subject already in the +/// world, or already claimed in `declared` (which it joins). Every door that +/// admits or loads subjects calls this, so none can decide otherwise. +pub(super) fn import_key_fault<'a>( + key: &'a ImportKey, + held: &BTreeSet<&ImportKey>, + declared: &mut BTreeSet<&'a ImportKey>, +) -> Option { + if !key.is_canonical() { + Some(ImportKeyFault::Malformed) + } else if held.contains(key) { + Some(ImportKeyFault::Held) + } else if !declared.insert(key) { + Some(ImportKeyFault::Duplicate) + } else { + None + } +} + +/// `position` is the subject's presence: one place it stands in. A subject +/// declared without one is unplaced until a later pass gives placement an owner. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct SubjectDeclaration { + pub(crate) handle: DraftHandle, + pub(crate) label: String, + pub(crate) kind: SubjectKind, + pub(crate) controller: NewController, + /// The catalog entries this subject may exercise. Every entry is a + /// reference, so a genesis patch declares a catalog and grants from it + /// atomically. + pub(crate) affordances: BTreeSet>, + pub(crate) position: Option>, + /// The record this subject was imported from, if any. Absent from a + /// subject nobody imported, so such a world's state and digests are what + /// they were before import keys existed. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) import_key: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct EntityDeclaration { + pub(crate) handle: DraftHandle, + pub(crate) label: String, + pub(crate) kind: EntityKind, + /// Legal only for `EntityKind::Place`, and only ever names a place. + pub(crate) container: Option>, +} + +/// A declared route is open. A route that should start closed is `declare` plus +/// `CloseRoute` in the same patch, so `open` has one writer family. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct RouteDeclaration { + pub(crate) handle: DraftHandle, + pub(crate) label: String, + pub(crate) from: Ref, + pub(crate) to: Ref, + pub(crate) access: AccessKind, + pub(crate) cost: Cost, +} + +/// A fact's label is a short authored name ("the flooding of the lower hinge"), +/// never a transcript: the statement is never copied into the label and the +/// label is never derived from the statement, so the utterance has exactly one +/// home in state. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct FactDeclaration { + pub(crate) handle: DraftHandle, + pub(crate) label: String, + pub(crate) statement: Statement, + pub(crate) standing: FactStandingRef, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct ChannelDeclaration { + pub(crate) handle: DraftHandle, + pub(crate) label: String, + pub(crate) reach: ReachRef, + pub(crate) controller: Option>, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "type", rename_all = "snake_case")] +pub(crate) enum Declaration { + Subject(SubjectDeclaration), + /// Places and resources only. `Fact` and `Channel` carry a payload and have + /// their own declarations, so a referenceable empty one is unrepresentable. + Entity(EntityDeclaration), + Route(RouteDeclaration), + Affordance(AffordanceDeclaration), + Fact(FactDeclaration), + Channel(ChannelDeclaration), +} + +/// The operations that change a component of an already canonical structure. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "op", rename_all = "snake_case")] +pub(crate) enum ComponentOp { + Relocate { + subject: Ref, + via: Ref, + }, + OpenRoute { + route: Ref, + }, + CloseRoute { + route: Ref, + }, + AlterCost { + route: Ref, + cost: Cost, + }, + Transfer { + from: Ref, + to: Ref, + resource: Ref, + qty: Quantity, + }, + /// One-for-one relabel: the same `qty` leaves `from_resource` and arrives in + /// `into_resource`, held by the same subject. A ratio would be a recipe, and + /// recipes belong to the consumer that owns production; the op shape makes a + /// non-conserving transform unrepresentable rather than merely checkable. A + /// world that needs lossy conversion writes `Transform` plus `Consume`, and + /// both terms then appear in the ledger. + Transform { + holder: Ref, + from_resource: Ref, + into_resource: Ref, + qty: Quantity, + }, + Consume { + holder: Ref, + resource: Ref, + qty: Quantity, + }, + /// The only creation path for quantity, in every lane including genesis. Its + /// `evidence` must appear in the same patch's `evidence` list, which makes + /// creation attributable; the commit chain then makes it tamper-evident. + Admit { + holder: Ref, + resource: Ref, + qty: Quantity, + evidence: EvidenceRef, + }, + /// Creates quantity with no receipt. Only `Play` may write it; every other + /// author creates quantity through `Admit` and its evidence. + Mint { + holder: Ref, + resource: Ref, + qty: Quantity, + }, + Bind { + subject: Ref, + target: DependencyRef, + }, + Release { + subject: Ref, + target: DependencyRef, + }, + /// Adds one grant. An identical grant is `NoOperationEffect`; one that + /// overlaps another the holder already has is `OverlappingJurisdiction`. + GrantAuthority { + holder: Ref, + grant: AuthorityGrantRef, + }, + RevokeAuthority { + holder: Ref, + grant: AuthorityGrantRef, + }, + /// Creates or reconstitutes an office, preserving any sitting incumbent. + /// Clipping an office's powers under a sitting incumbent is a political + /// act, and this is how it is written. + OpenOffice { + institution: Ref, + office: OfficeName, + delegated: BTreeSet, + }, + CloseOffice { + institution: Ref, + office: OfficeName, + }, + InstallIncumbent { + institution: Ref, + office: OfficeName, + incumbent: Ref, + }, + VacateOffice { + institution: Ref, + office: OfficeName, + }, + OpenForum { + grievance: GrievanceKindName, + forum: Ref, + standing: AuthorityTargetRef, + }, + CloseForum { + grievance: GrievanceKindName, + }, + /// Source is authored: `Witnessed` by an author or an affordance, + /// `Evidenced` only over a `Canonical` fact. + AcquireKnowledge { + subject: Ref, + fact: Ref, + source: AuthoredSource, + confidence: Confidence, + }, + /// One telling. It stores the audience, never the recipients: the fan-out is + /// re-derived at apply from live `positions` and `channels`. + Communicate { + speaker: Ref, + fact: Ref, + to: AudienceRef, + }, + /// One witnessed event over a place subtree: a beacon, a bell, a blast, an + /// asteroid. It names no speaker, because the row it lands is + /// `KnowledgeSource::Witnessed` — there is no teller to forge and none is + /// implied. It stores the place, never the recipients: the subtree is + /// re-derived at apply from live `positions`. Everyone already holding the + /// fact is untouched, and a witness that reaches nobody is refused. + Witness { + fact: Ref, + place: Ref, + confidence: Confidence, + }, + Forget { + subject: Ref, + fact: Ref, + }, + SetReach { + channel: Ref, + reach: ReachRef, + }, + SetController { + channel: Ref, + controller: Option>, + }, + /// Sets, whole, what a subject carries as lived meaning. Identical material + /// is `NoOperationEffect`; any non-canonical text is `NoncanonicalText`. + SetPersonaMaterial { + subject: Ref, + values: Vec, + voice: Statement, + memories: Vec, + reads: Vec, + }, + /// Two identical creations are two commitments, not `NoOperationEffect`: + /// the key is command-derived so they cannot collide, and two promises of + /// the same thing to the same counterparty are two promises. This is where + /// a commitment differs from a grant, a holding, and a dependency, all of + /// which are set-shaped. + CreateCommitment { + subject: Ref, + counterparty: Option>, + kind: CommitmentKind, + due: FictionalMinutes, + period: Option, + checks: Vec, + statement: Statement, + }, + /// Removes the commitment and every pressure row sourced by it. Fulfilment, + /// default, and release are one write: the kernel never learns who invoked + /// an operation, so three names would be three spellings of one removal + /// with a distinction only a consumer can read. + DischargeCommitment { + subject: Ref, + key: CommitmentKey, + }, + /// Insert-or-add, saturating. With absence meaning zero, creation and + /// advance are the same write. + AdvancePressure { + source: PressureSourceRef, + target: Ref, + by: PressureMagnitude, + }, + /// Saturating subtract; removal at zero. + ReducePressure { + source: PressureSourceRef, + target: Ref, + by: PressureMagnitude, + }, + ResolvePressure { + source: PressureSourceRef, + target: Ref, + }, + /// Ends a subject's turn for good: no opportunity, no position, no + /// audience, its history kept. Only the owner and `Play` may write it. + Retire { + subject: Ref, + }, + /// Grants one more standing catalog entry to an existing subject. Only the + /// owner (including the seed lane, the owner in Draft) and `Play` may + /// write it: a grant is authority, not structure, so a confined author is + /// refused whatever ground the subject stands on. + GrantAffordance { + subject: Ref, + affordance: Ref, + }, + /// Revokes a grant. Refused if it would leave a controlled subject with + /// none: `derive_opportunities` requires at least one. + RevokeAffordance { + subject: Ref, + affordance: Ref, + }, +} + +/// What an Active `AdmitPatch` answers. Draft answers nothing; Active must +/// answer a boundary the kernel currently derives or a jurisdiction whose +/// deficit is nonzero, and the commit must satisfy what it answered. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "answer", rename_all = "snake_case")] +pub enum PatchAnswer { + Boundary(super::CausalBoundary), + Deficit(JurisdictionKey), +} + +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct WorldPatch { + pub(crate) declarations: Vec, + pub(crate) operations: Vec, + pub(crate) evidence: Vec, +} + +impl WorldPatch { + /// Whether any `SetPersonaMaterial` operation in this patch targets a + /// subject the patch does not itself declare — an existing, canonical + /// subject (`Ref::Existing`) rather than a draft handle this same patch's + /// own declarations introduced (`Ref::Draft`). `WorldPatch`'s fields are + /// `pub(crate)`, so a consumer that must refuse this shape (PA.f61: the + /// play agent may author a brand-new Persona's material, but never + /// rewrite an existing one's) reads it through this query rather than + /// parsing the patch's own JSON to decide. + pub fn sets_persona_of_existing_subject(&self) -> bool { + self.operations.iter().any(|operation| { + matches!( + operation, + ComponentOp::SetPersonaMaterial { + subject: Ref::Existing(_), + .. + } + ) + }) + } +} + +/// The one byte bound on a `WorldPatch` frame from any external source, and +/// the three item bounds on a `WorldPatch` as a value. One owner, two +/// consumers: the consumer ingress decodes against them through +/// `decode_patch`, and the elaboration lane checks its own assembled draft +/// against the same three item caps through `check_patch_caps`, before +/// submission. +pub(crate) const MAX_PATCH_BYTES: usize = 256 * 1024; +pub(crate) const MAX_PATCH_DECLARATIONS: usize = 64; +pub(crate) const MAX_PATCH_OPERATIONS: usize = 128; +pub(crate) const MAX_PATCH_EVIDENCE: usize = 64; + +/// Why a patch was refused before the resolver ever saw it. Not a second +/// structural vocabulary: nothing here reads world state. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum PatchDecodeError { + TooLarge { bytes: usize }, + NotCanonical, + Malformed, + TooManyDeclarations { count: usize }, + TooManyOperations { count: usize }, + TooManyEvidence { count: usize }, +} + +/// The one decode owner for a `WorldPatch` from a byte source. The byte cap is +/// applied to the frame before `rmp_serde` sees it, so no item is deserialized +/// out of a frame the world would not accept; the item caps are checked on the +/// decoded value before `resolve_patch`, which is the first thing that costs +/// `state ∪ patch`. +pub(crate) fn decode_patch(bytes: &[u8]) -> Result { + if bytes.len() > MAX_PATCH_BYTES { + return Err(PatchDecodeError::TooLarge { bytes: bytes.len() }); + } + let patch: WorldPatch = + rmp_serde::from_slice(bytes).map_err(|_| PatchDecodeError::Malformed)?; + // The canonical round-trip the journal and the presence route already + // require, so one frame has one encoding. + if rmp_serde::to_vec_named(&patch).map_err(|_| PatchDecodeError::Malformed)? != bytes { + return Err(PatchDecodeError::NotCanonical); + } + check_patch_caps(&patch)?; + Ok(patch) +} + +/// The same three item caps against an in-memory draft, for the lane that +/// builds rather than decodes. +pub(crate) fn check_patch_caps(patch: &WorldPatch) -> Result<(), PatchDecodeError> { + if patch.declarations.len() > MAX_PATCH_DECLARATIONS { + return Err(PatchDecodeError::TooManyDeclarations { + count: patch.declarations.len(), + }); + } + if patch.operations.len() > MAX_PATCH_OPERATIONS { + return Err(PatchDecodeError::TooManyOperations { + count: patch.operations.len(), + }); + } + if patch.evidence.len() > MAX_PATCH_EVIDENCE { + return Err(PatchDecodeError::TooManyEvidence { + count: patch.evidence.len(), + }); + } + Ok(()) +} + +/// One named structural check that a patch failed. A rejection carries the +/// complete set, never the first failure. It never enters `WorldState`, +/// `WorldEffect`, `CommandEnvelope`, or `WorldCommit`; the serde derives exist +/// for exactly one reader, the elaboration checkpoint, which is +/// controller-owned telemetry under its own row type and its own schema. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "mismatch", rename_all = "snake_case")] +pub enum Mismatch { + EmptyHandle { + position: usize, + }, + DuplicateHandle { + handle: DraftHandle, + }, + EmptyLabel { + handle: DraftHandle, + }, + /// The world is bound to a grammar and this affordance's kind is not one of + /// its verbs. + AffordanceKindNotInGrammar { + handle: DraftHandle, + }, + /// The kind is a verb of the bound grammar, but the declared roles are not + /// its signature (name, referent kind or order). + AffordanceRolesDisagreeWithGrammar { + handle: DraftHandle, + }, + /// The grammar binds the kernel's speak verb as anything but a Conversation. + SpeakRenderPathDisagreesWithGrammar { + handle: DraftHandle, + }, + /// An import key is empty, has whitespace, or is longer than 200 bytes in + /// either part. + MalformedImportKey { + handle: DraftHandle, + }, + /// Two subjects in one patch declare the same import key. + DuplicateImportKey { + handle: DraftHandle, + }, + /// A subject already in the world, retired or not, holds this import key. + ImportKeyHeld { + handle: DraftHandle, + }, + UnresolvedDraft { + site: Site, + referent: DraftHandle, + expected: RefKind, + }, + WrongKind { + site: Site, + referent: RefName, + expected: RefKind, + actual: RefKind, + }, + UnknownCanonical { + site: Site, + expected: RefKind, + }, + UnadmittedController { + handle: DraftHandle, + }, + /// A declared subject's controller and affordance grant do not pair: a + /// mirror was granted an affordance, or an ordinary controller was granted + /// none. `admit_resolved` re-decides the same rule. + ControllerGrantMismatch { + site: Site, + }, + EmptyEvidence { + position: usize, + }, + CanonicalCollision { + handle: DraftHandle, + }, + NoCanonicalChange, + /// A genesis-lane resolution (the same empty-state case `admits_human` + /// tests) declared no subject, so the world would have no decision + /// subject to admit. This is a rejected patch, not a corrupt journal: the + /// mailbox actor must survive it. + NoDecisionSubject, + /// A declared place contains itself through its container chain. + ContainmentCycle { + referent: DraftHandle, + }, + RouteSelfLoop { + referent: DraftHandle, + }, + InvalidCost { + site: Site, + }, + SubjectNotAtOrigin { + operation: usize, + }, + RouteClosed { + operation: usize, + }, + RouteAccessRestricted { + operation: usize, + }, + UnplacedSubject { + operation: usize, + }, + /// An operation that changes nothing is not a canonical change. + NoOperationEffect { + operation: usize, + }, + /// The holder does not hold enough. Absence is zero, so "holds none at all" + /// is this variant at the boundary rather than a second name. + InsufficientCustody { + operation: usize, + }, + /// A custody operation naming `Quantity(0)`: it moves nothing. + ZeroQuantity { + operation: usize, + }, + /// A credit that would leave a holding above `u64::MAX`. + QuantityOverflow { + operation: usize, + }, + /// An `Admit` whose `EvidenceRef` is not listed in this patch's `evidence`. + AdmitWithoutEvidence { + operation: usize, + }, + /// A `Bind` or `Release` naming the acting subject as its own target. + SelfDependency { + operation: usize, + }, + /// The candidate ledger does not balance for this resource: the total after + /// the patch is not the total before plus what was admitted and gained, less + /// what was consumed and spent. + CustodyNotConserved { + resource: RefName, + }, + /// `kind` is not `[a-z][a-z0-9_]{0,47}`, or a `Role` is not + /// `[a-z][a-z0-9_]{0,31}`. Tool and parameter names must be safe. + InvalidAffordanceName { + handle: DraftHandle, + }, + /// Two entries in the candidate graph share one kind name; the generated + /// tool catalog would have two tools with one name. + DuplicateAffordanceKind { + handle: DraftHandle, + }, + DuplicateRole { + handle: DraftHandle, + role: Role, + }, + /// A precondition or a slot names a role the entry does not declare. + UnknownRole { + handle: DraftHandle, + role: Role, + }, + /// A declared role's `RefKind` cannot serve the position that reads it, or + /// names a namespace no invocation target can bind. + RoleKindUnfit { + handle: DraftHandle, + role: Role, + }, + SlotRoleArity { + handle: DraftHandle, + slot: usize, + }, + /// The slot's `Bounds` variant does not match its `op_kind`'s dimension, or + /// the ceiling is zero, or a cost ceiling is outside `1..=MAX_ROUTE_COST`. + SlotBoundMismatch { + handle: DraftHandle, + slot: usize, + }, + NoOutcomeBand { + handle: DraftHandle, + }, + ZeroBandWeight { + handle: DraftHandle, + band: usize, + }, + /// A band names a slot index the entry does not have. + DanglingBandEffect { + handle: DraftHandle, + band: usize, + }, + /// A band's `effects` are not strictly increasing. + BandEffectsNotCanonical { + handle: DraftHandle, + band: usize, + }, + /// No effect slots and no speech: the entry can never change anything. + InertAffordance { + handle: DraftHandle, + }, + /// An `OfficeName`, `AuthorityKindName`, or `GrievanceKindName` that is not + /// `[a-z][a-z0-9_]{0,47}`. + InvalidCivicName { + site: Site, + }, + /// `OpenOffice` lending no authority kind. + EmptyDelegation { + operation: usize, + }, + /// The institution named by an office operation is not + /// `SubjectKind::Institution`. + OfficeOnNonInstitution { + operation: usize, + }, + /// An incumbent that is not `SubjectKind::Person`. This is the check that + /// keeps an institution's operational organ and its person-shaped voice two + /// subjects joined by an office. + OfficeHolderNotPerson { + operation: usize, + }, + /// This person already occupies another office of this institution. + DuplicateIncumbency { + operation: usize, + }, + /// `InstallIncumbent`, `VacateOffice`, or `CloseOffice` naming an office the + /// institution does not have. + UnknownOffice { + operation: usize, + }, + /// `CloseForum` naming a grievance no forum takes. + UnknownForum { + operation: usize, + }, + /// One subject would hold two grants of the same kind over overlapping + /// targets, from any combination of direct grant and office delegation. + /// Overlap between *different* subjects is layered government and legal: + /// `Authorized` is a permission predicate, not an exclusivity claim, and + /// this rule exists so nothing ever has to arbitrate between two sources. + OverlappingJurisdiction { + operation: usize, + }, + /// A catalog entry declares a role named `actor`, which the kernel binds. + ReservedRole { + handle: DraftHandle, + }, + /// An `EntityDeclaration` naming `Fact` or `Channel`. Those kinds carry a + /// payload and have their own declaration; a payload-less one would make a + /// referenceable, empty fact a legal state. + PayloadEntityKind { + handle: DraftHandle, + }, + /// A `Canonical` fact declaration whose `EvidenceRef` is not listed in this + /// patch's `evidence`. + FactWithoutEvidence { + handle: DraftHandle, + }, + EmptyStatement { + handle: DraftHandle, + }, + /// A commitment statement or a piece of persona material that is empty, + /// padded, or spans lines. + NoncanonicalText { + operation: usize, + }, + /// `AcquireKnowledge { source: Evidenced }` over a `Claimed` fact. + EvidencedKnowledgeOfClaim { + operation: usize, + }, + /// A `Communicate` whose speaker is neither inside the audience nor the + /// channel's controller. + SpeakerOutsideAudience { + operation: usize, + }, + /// A catalog entry with `carries_speech` and no `CanBroadcast` or + /// `CanReach`: its speech would have no audience to lower. + SpeechWithoutAudience { + handle: DraftHandle, + }, + /// More than one, so the lowering could not choose. + AmbiguousSpeechAudience { + handle: DraftHandle, + }, + /// A `Routine` with no period, or a non-`Routine` with one. + CommitmentPeriodMismatch { + operation: usize, + }, + /// A non-`Routine` carrying checks. Nothing would ever evaluate them. + ChecksOnNonRoutine { + operation: usize, + }, + /// `due <= now` at creation. A promise cannot be born past due; it would + /// press on its subject on the very next tick with no chance to act. + CommitmentDueInThePast { + operation: usize, + }, + /// `counterparty == subject`. + SelfCommitment { + operation: usize, + }, + /// A goal is a promise to oneself, and a promise to another is an + /// obligation. This keeps the scale count's `Goal` clause meaning one thing. + GoalWithCounterparty { + operation: usize, + }, + /// `DischargeCommitment` naming a key the subject does not hold. + UnknownCommitment { + operation: usize, + }, + /// A scale-intent jurisdiction root that is not a declared place. + UnknownJurisdictionRoot { + handle: DraftHandle, + }, + /// The permille weights sum over 1000: weights distribute the target and + /// never raise it. + ScaleWeightsExceedWhole, + /// A lens weight set with no nonzero weight, at genesis or in + /// `SetLensWeights`. A single zero weight is admitted and never draws. + LensWeightsNeverDraw, + /// A jurisdictional author wrote outside its jurisdiction. The owner is + /// unconfined and never sees this. + OutsideJurisdiction { + site: Site, + }, + /// A `Ruled` fact or a `Mint` was written by a caller other than the play + /// authority. + RuledWithoutAuthority { + site: Site, + }, + /// `Retire` named an `ExternallyControlled` subject: a mirror is owned by + /// another world, so this one cannot retire it. + RetiresAMirror { + operation: usize, + }, + /// `Retire` named a `Human`-controlled subject while the world is still in + /// `Draft`. A human's Draft approval cannot be removed by removing the + /// human; the same retire is admitted once the world is `Active`. + RetiresAnApprover { + operation: usize, + }, + /// `Communicate`, `AcquireKnowledge`, `Forget`, or `InstallIncumbent` + /// named a retired subject as the one acting, learning, forgetting, or + /// taking office. A retired subject is a body, not an actor: it may still + /// be a holdings source (looted), a channel member, or a route endpoint, + /// but it cannot be the one who speaks, knows, or holds office. + RetiredSubjectActed { + operation: usize, + }, + /// `GrantAffordance` or `RevokeAffordance` named a retired or an + /// `ExternallyControlled` subject: neither holds a grant this patch may + /// touch. + GrantsOutsideControl { + operation: usize, + }, + /// A `RevokeAffordance` that would leave a controlled subject with no + /// affordance at all. `derive_opportunities` requires at least one; a + /// subject is never left mute. + WouldLeaveSubjectMute { + operation: usize, + }, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(super) struct EntityRecord { + pub(super) label: String, + pub(super) kind: EntityKind, + /// `Some` only for `EntityKind::Place`, and only ever a place. + pub(super) container: Option, +} + +/// One variant per edge kind that has a shape, so no record carries fields that +/// are meaningless for its discriminator. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub(super) enum EdgeRecord { + Route { + label: String, + from: EntityId, + to: EntityId, + access: AccessKind, + cost: Cost, + open: bool, + }, +} + +impl EdgeRecord { + pub(super) fn endpoints(&self) -> (EntityId, EntityId) { + match self { + Self::Route { from, to, .. } => (*from, *to), + } + } + + pub(super) fn label(&self) -> &str { + match self { + Self::Route { label, .. } => label, + } + } + + pub(super) fn cost(&self) -> Cost { + match self { + Self::Route { cost, .. } => *cost, + } + } + + pub(super) fn access(&self) -> &AccessKind { + match self { + Self::Route { access, .. } => access, + } + } + + pub(super) fn is_open(&self) -> bool { + match self { + Self::Route { open, .. } => *open, + } + } + + pub(super) fn set_open(&mut self, value: bool) { + match self { + Self::Route { open, .. } => *open = value, + } + } + + pub(super) fn set_cost(&mut self, value: Cost) { + match self { + Self::Route { cost, .. } => *cost = value, + } + } +} + +/// The handle-to-ID binding table for one subject. The handle is commit-scoped +/// provenance; it never enters `WorldState`. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(super) struct ResolvedSubject { + pub(super) handle: DraftHandle, + pub(super) subject_id: SubjectId, + pub(super) subject: SubjectState, + pub(super) controller: ControllerAssignment, + pub(super) affordances: BTreeSet, + pub(super) position: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(super) struct ResolvedEntity { + pub(super) handle: DraftHandle, + pub(super) entity_id: EntityId, + pub(super) entity: EntityRecord, +} + +/// The handle-to-ID binding for one catalog entry. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(super) struct ResolvedAffordance { + pub(super) handle: DraftHandle, + pub(super) affordance_id: AffordanceId, + pub(super) affordance: Affordance, +} + +/// A declared fact: one `entities` row and one `facts` row, allocated together +/// so the bijection has one writer. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(super) struct ResolvedFact { + pub(super) handle: DraftHandle, + pub(super) entity_id: EntityId, + pub(super) entity: EntityRecord, + pub(super) fact: FactRecord, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(super) struct ResolvedChannel { + pub(super) handle: DraftHandle, + pub(super) entity_id: EntityId, + pub(super) entity: EntityRecord, + pub(super) channel: ChannelRecord, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(super) struct ResolvedRoute { + pub(super) handle: DraftHandle, + pub(super) edge_id: EdgeId, + pub(super) edge: EdgeRecord, +} + +/// A lowered operation. `Relocate` carries no endpoints: they are read from the +/// route at apply time, so a forged effect cannot assert a destination the route +/// does not have. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "op", rename_all = "snake_case")] +pub(crate) enum ResolvedOp { + Relocate { + subject_id: SubjectId, + edge_id: EdgeId, + }, + OpenRoute { + edge_id: EdgeId, + }, + CloseRoute { + edge_id: EdgeId, + }, + AlterCost { + edge_id: EdgeId, + cost: Cost, + }, + Transfer { + from: SubjectId, + to: SubjectId, + resource: EntityId, + qty: Quantity, + }, + Transform { + holder: SubjectId, + from_resource: EntityId, + into_resource: EntityId, + qty: Quantity, + }, + Consume { + holder: SubjectId, + resource: EntityId, + qty: Quantity, + }, + Admit { + holder: SubjectId, + resource: EntityId, + qty: Quantity, + evidence: EvidenceRef, + }, + Mint { + holder: SubjectId, + resource: EntityId, + qty: Quantity, + }, + Bind { + subject: SubjectId, + target: DependencyTarget, + }, + Release { + subject: SubjectId, + target: DependencyTarget, + }, + GrantAuthority { + holder: SubjectId, + grant: AuthorityGrant, + }, + RevokeAuthority { + holder: SubjectId, + grant: AuthorityGrant, + }, + OpenOffice { + institution: SubjectId, + office: OfficeName, + delegated: BTreeSet, + }, + CloseOffice { + institution: SubjectId, + office: OfficeName, + }, + InstallIncumbent { + institution: SubjectId, + office: OfficeName, + incumbent: SubjectId, + }, + VacateOffice { + institution: SubjectId, + office: OfficeName, + }, + OpenForum { + grievance: GrievanceKindName, + forum: SubjectId, + standing: AuthorityTarget, + }, + CloseForum { + grievance: GrievanceKindName, + }, + AcquireKnowledge { + subject: SubjectId, + fact: EntityId, + source: AuthoredSource, + confidence: Confidence, + }, + /// Stores the audience, never the recipients. `apply_operation` re-derives + /// the fan-out from live `positions`/`channels`, exactly as `Relocate` + /// stores `edge_id` and re-derives the destination, so a forged effect + /// cannot assert a landing the world does not have. + Communicate { + speaker: SubjectId, + fact: EntityId, + to: Audience, + }, + /// A visible act: the actor's own sentence, seen by everyone standing in + /// the actor's place. Lowered only by the kernel's speech path beside + /// `AssertClaim`, never by a patch, so no seed or elaborator can move a + /// person's body from outside the person. There is no audience field: a + /// display cannot go down a channel, and the room is re-derived from live + /// `positions` at apply, so a forged effect cannot assert a landing the + /// world does not have. + Display { + actor: SubjectId, + fact: EntityId, + }, + /// Stores the place, never the recipients. `apply_operation` re-derives the + /// subtree from live `positions`, so a forged effect cannot assert a + /// landing the world does not have. There is no speaker field, so this + /// operation cannot write `KnowledgeSource::Told` however it is forged. + Witness { + fact: EntityId, + place: EntityId, + confidence: Confidence, + }, + Forget { + subject: SubjectId, + fact: EntityId, + }, + SetReach { + channel: EntityId, + reach: Reach, + }, + SetController { + channel: EntityId, + controller: Option, + }, + SetPersonaMaterial { + subject: SubjectId, + material: PersonaMaterial, + }, + /// Kernel-only: no [`ComponentOp`] twin, because no proposer may author one. + /// Synthesized by `action::exercise` for a speech-carrying invocation and by + /// nothing else. Inserts the entity row and the `facts` row; it writes no + /// knowledge, because a speaker's own knowledge of its claim is not implied. + AssertClaim { + fact: EntityId, + statement: Statement, + by: SubjectId, + }, + CreateCommitment { + subject: SubjectId, + key: CommitmentKey, + commitment: Commitment, + }, + DischargeCommitment { + subject: SubjectId, + key: CommitmentKey, + }, + AdvancePressure { + source: PressureSource, + target: SubjectId, + by: PressureMagnitude, + }, + ReducePressure { + source: PressureSource, + target: SubjectId, + by: PressureMagnitude, + }, + ResolvePressure { + source: PressureSource, + target: SubjectId, + }, + Retire { + subject: SubjectId, + }, + GrantAffordance { + subject: SubjectId, + affordance: AffordanceId, + }, + RevokeAffordance { + subject: SubjectId, + affordance: AffordanceId, + }, +} + +/// One resource's movement across a whole patch. Accumulators are `u128` so an +/// intermediate total cannot overflow while a stored per-holder `Quantity` stays +/// `u64`. +#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)] +pub(super) struct LedgerDelta { + pub(super) before: u128, + pub(super) after: u128, + pub(super) admitted: u128, + pub(super) consumed: u128, + pub(super) gained: u128, + pub(super) spent: u128, +} + +/// The only statement of custody conservation, called by the resolver over the +/// candidate map and again by `admit_resolved` over the committed partitions. +/// Returns the first resource whose ledger does not balance, in key order, so +/// the verdict is deterministic. +/// +/// `Transfer` contributes to no term: its correctness is *proven by* this +/// equation, because a transfer that moved a different amount out than in breaks +/// the total for that resource. `Transform` contributes the same `qty` to one +/// `spent` and one `gained`, so the one-for-one rule is this equation restricted +/// to a single operation. Nothing else states conservation anywhere. +pub(super) fn check_ledger(deltas: &BTreeMap) -> Option { + deltas + .iter() + .find(|(_, delta)| { + let credited = delta + .before + .checked_add(delta.admitted) + .and_then(|total| total.checked_add(delta.gained)); + let expected = credited + .and_then(|total| total.checked_sub(delta.consumed)) + .and_then(|total| total.checked_sub(delta.spent)); + expected != Some(delta.after) + }) + .map(|(resource, _)| resource.clone()) +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(super) struct ResolvedPatch { + pub(super) subjects: Vec, + pub(super) entities: Vec, + pub(super) routes: Vec, + pub(super) affordances: Vec, + pub(super) facts: Vec, + pub(super) channels: Vec, + pub(super) operations: Vec, + pub(super) evidence: Vec, + /// `Some` on the genesis lane and nowhere else: `CommandBody::AdmitPatch` + /// carries no intent, so the write-once rule is the command shape rather + /// than a check. + pub(super) scale_intent: Option, + /// `Some` on the genesis lane and nowhere else, as `scale_intent` is. After + /// genesis the weights change only through `SetLensWeights`. + pub(super) lens_weights: Option, +} + +impl ResolvedPatch { + pub(super) fn declares_nothing(&self) -> bool { + self.subjects.is_empty() + && self.entities.is_empty() + && self.routes.is_empty() + && self.affordances.is_empty() + && self.facts.is_empty() + && self.channels.is_empty() + && self.evidence.is_empty() + } +} + +const SUBJECT_NAMESPACE: &str = "ghostlight.id.subject.v1"; +pub(super) const ENTITY_NAMESPACE: &str = "ghostlight.id.entity.v1"; +const EDGE_NAMESPACE: &str = "ghostlight.id.edge.v1"; +const CONTROLLER_NAMESPACE: &str = "ghostlight.id.controller.v1"; +const AFFORDANCE_NAMESPACE: &str = "ghostlight.id.affordance.v1"; + +const PLACE: RefKind = RefKind::Entity(EntityKind::Place); +const FACT: RefKind = RefKind::Entity(EntityKind::Fact); +const CHANNEL: RefKind = RefKind::Entity(EntityKind::Channel); +const ROUTE: RefKind = RefKind::Edge(EdgeKind::Route); +const ANY_SUBJECT: RefKind = RefKind::Subject(None); + +/// A candidate-graph key: a structure this patch declares, or one the world +/// already holds. Candidate topology is checked before any ID is minted, so it +/// is keyed by reference rather than by canonical ID. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +enum Key { + Existing(Id), + Draft(DraftHandle), +} + +fn key_of(reference: &Ref) -> Key { + match reference { + Ref::Existing(id) => Key::Existing(*id), + Ref::Draft(handle) => Key::Draft(handle.clone()), + } +} + +/// [`DependencyTarget`] over candidate keys, so a dependency on a structure this +/// patch declares is checked before any ID is minted. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +enum TargetKey { + Resource(Key), + Route(Key), + Subject(Key), +} + +/// [`PressureSource`] over candidate keys. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +enum PressureSourceKey { + Commitment { + subject: Key, + key: CommitmentKey, + }, + Dependency(TargetKey), + Subject(Key), +} + +/// [`AuthorityTarget`] over candidate keys, so a grant over a place this patch +/// declares is checked before any ID is minted. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +enum AuthorityTargetKey { + Subject(Key), + PlaceSubtree(Key), +} + +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +struct GrantKey { + kind: AuthorityKindName, + over: AuthorityTargetKey, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +struct OfficeCandidate { + incumbent: Option>, + delegated: BTreeSet, +} + +/// Whether two jurisdictions of one kind cover common ground. Structural on +/// purpose: identity for named subordinates, containment for territory, and +/// never across the two, so the answer cannot decay when a subject walks +/// somewhere. Containment is fixed at declaration, so every way of creating an +/// overlap is a checked operation. +fn candidate_targets_overlap( + left: &AuthorityTargetKey, + right: &AuthorityTargetKey, + containers: &BTreeMap, Key>, +) -> bool { + match (left, right) { + (AuthorityTargetKey::Subject(one), AuthorityTargetKey::Subject(other)) => one == other, + (AuthorityTargetKey::PlaceSubtree(one), AuthorityTargetKey::PlaceSubtree(other)) => { + key_covers_place(one, other, containers) || key_covers_place(other, one, containers) + } + _ => false, + } +} + +/// Whether a candidate `Subject` grant target and a candidate `PlaceSubtree` +/// grant target of one kind name overlapping ground: a `PlaceSubtree` grant +/// covers a `Subject` grant's target when the subject's committed position +/// sits under that subtree. Checked live against `state` rather than the +/// candidate graph, because `covers` reads committed position and +/// containment, not anything a patch declares; a target still in this +/// patch's drafts has no committed position and so cannot overlap here. This +/// is the one cross-shape case `candidate_targets_overlap` leaves alone by +/// construction — same-shape overlap is its job, not this one's. +fn grant_targets_nest( + state: &super::WorldState, + left: &AuthorityTargetKey, + right: &AuthorityTargetKey, +) -> bool { + let place_and_subject = |a: &AuthorityTargetKey, b: &AuthorityTargetKey| match (a, b) { + ( + AuthorityTargetKey::PlaceSubtree(Key::Existing(place)), + AuthorityTargetKey::Subject(Key::Existing(subject_id)), + ) => Some((*place, *subject_id)), + _ => None, + }; + place_and_subject(left, right) + .or_else(|| place_and_subject(right, left)) + .is_some_and(|(place, subject_id)| { + super::covers( + state, + AuthorityTarget::PlaceSubtree(place), + super::Target::Subject(subject_id), + ) + }) +} + +fn target_key_of(target: AuthorityTarget) -> AuthorityTargetKey { + match target { + AuthorityTarget::Subject(subject_id) => { + AuthorityTargetKey::Subject(Key::Existing(subject_id)) + } + AuthorityTarget::PlaceSubtree(entity_id) => { + AuthorityTargetKey::PlaceSubtree(Key::Existing(entity_id)) + } + } +} + +fn grant_key_of(grant: &AuthorityGrant) -> GrantKey { + GrantKey { + kind: grant.kind.clone(), + over: target_key_of(grant.over), + } +} + +/// The candidate authority of one subject, projected to the canonical referents +/// [`covers`](super::covers) reads. A grant naming structure this patch declares +/// cannot cover a place an already-canonical route reaches, so the projection +/// loses nothing the `Restricted` rule asks about. +fn canonical_grants(grants: &BTreeSet) -> BTreeSet { + grants + .iter() + .filter_map(|grant| { + let over = match &grant.over { + AuthorityTargetKey::Subject(Key::Existing(subject_id)) => { + AuthorityTarget::Subject(*subject_id) + } + AuthorityTargetKey::PlaceSubtree(Key::Existing(entity_id)) => { + AuthorityTarget::PlaceSubtree(*entity_id) + } + _ => return None, + }; + Some(AuthorityGrant { + kind: grant.kind.clone(), + over, + }) + }) + .collect() +} + +/// Own grants plus what every held office lends, over the candidate graph. The +/// canonical twin is `scope_components` plus `effective_authority`; this one +/// answers the same question before any ID is minted. +fn candidate_effective_authority( + holder: &Key, + authority: &BTreeMap, BTreeSet>, + selection: &BTreeMap<(Key, OfficeName), OfficeCandidate>, + retired: &BTreeSet>, +) -> BTreeSet { + let mut effective = authority.get(holder).cloned().unwrap_or_default(); + for ((institution, _), office) in selection { + if office.incumbent.as_ref() != Some(holder) { + continue; + } + // A retired institution lends nothing, the same predicate + // `delegated_authority` reads canonically: `Retire` does not vacate + // offices, so the resolver and the kernel must not disagree about + // whether a dead institution's grants still reach its office-holders. + if retired.contains(institution) { + continue; + } + for grant in authority.get(institution).into_iter().flatten() { + if office.delegated.contains(&grant.kind) { + effective.insert(grant.clone()); + } + } + } + effective +} + +/// A fact in the candidate graph. Only its standing matters to resolution: the +/// statement is never read and never compared. +#[derive(Clone, Debug, PartialEq, Eq)] +enum FactCandidate { + Canonical, + Claimed(Key), + Ruled, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +enum ReachKey { + Subjects(BTreeSet>), + Place(Key), +} + +#[derive(Clone, Debug, PartialEq, Eq)] +struct ChannelCandidate { + reach: ReachKey, + controller: Option>, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +enum KnowledgeSourceKey { + Witnessed, + Told { + by: Key, + via: Option>, + }, + Seen { + by: Key, + }, + Evidenced, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +struct KnowledgeCandidate { + confidence: Confidence, + source: KnowledgeSourceKey, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +enum AudienceKey { + Colocated, + Channel(Key), +} + +/// Whether a subject is inside an audience over the candidate graph: the same +/// question `audience()` answers over committed state, asked before any ID is +/// minted. A controller is inside its own channel's audience for the purpose of +/// speaking on it — the horn belongs to the temple. +fn candidate_in_audience( + subject: &Key, + audience: &AudienceKey, + speaker: &Key, + positions: &BTreeMap, Key>, + channels: &BTreeMap, ChannelCandidate>, + containers: &BTreeMap, Key>, +) -> bool { + match audience { + AudienceKey::Colocated => match (positions.get(speaker), positions.get(subject)) { + (Some(here), Some(there)) => here == there, + _ => false, + }, + AudienceKey::Channel(channel) => { + let Some(record) = channels.get(channel) else { + return false; + }; + if record.controller.as_ref() == Some(subject) { + return true; + } + match &record.reach { + ReachKey::Subjects(members) => members.contains(subject), + ReachKey::Place(root) => positions + .get(subject) + .is_some_and(|place| key_covers_place(root, place, containers)), + } + } + } +} + +#[derive(Clone, Debug)] +struct RouteCandidate { + from: Key, + to: Key, + access: AccessKind, + cost: Cost, + open: bool, +} + +/// The only canonical ID allocator, called from exactly two sites: +/// [`resolve_patch`] and `action::exercise`. Deterministic on purpose: journal +/// replay recomputes `reduce` and requires effect equality, so a reduce arm can +/// never draw a `Uuid::new_v4`. Preimage fields are length-prefixed where they +/// are variable-width, so the concatenation is unambiguous — `discriminator` +/// included: a bare presence byte followed by a length prefix means +/// `Some("")` and `None` write different bytes, where an unprefixed +/// `Some("")` would have written nothing, same as `None`. +pub(super) fn derive_id( + namespace: &str, + world_id: WorldId, + command_id: CommandId, + handle: &DraftHandle, + discriminator: Option<&str>, +) -> Uuid { + let mut hasher = Sha256::new(); + hasher.update(namespace.as_bytes()); + hasher.update(world_id.0.as_bytes()); + hasher.update(command_id.0.as_bytes()); + hasher.update((handle.0.len() as u64).to_be_bytes()); + hasher.update(handle.0.as_bytes()); + match discriminator { + Some(discriminator) => { + hasher.update([1u8]); + hasher.update((discriminator.len() as u64).to_be_bytes()); + hasher.update(discriminator.as_bytes()); + } + None => hasher.update([0u8]), + } + let mut bytes = [0u8; 16]; + bytes.copy_from_slice(&hasher.finalize()[..16]); + Uuid::from_bytes(bytes) +} + +pub(super) fn is_canonical_text(value: &str) -> bool { + !value.trim().is_empty() && value.trim() == value +} + +pub(super) fn is_valid_cost(cost: Cost) -> bool { + (1..=MAX_ROUTE_COST).contains(&cost.0) +} + +/// The one role name the kernel owns. A catalog entry may not declare it and an +/// invocation may not bind it: stage 2 binds it to the acting subject, so a slot +/// that must land on the actor — the payee of a levy, say — says so instead of +/// letting the proposer point it at a friend. +pub(super) const ACTOR_ROLE: &str = "actor"; + +/// Authority kinds, office names, and grievance kinds share the affordance +/// alphabet: world-declared, kernel-opaque, and safe to surface in a generated +/// tool description. +pub(super) fn is_civic_name(value: &str) -> bool { + is_tool_name(value, 48) +} + +/// `[a-z][a-z0-9_]{0,max-1}`. Affordance kinds and roles become generated tool +/// and parameter names, so the alphabet is the safe one and the bound is stated +/// rather than assumed. +fn is_tool_name(value: &str, max: usize) -> bool { + let mut characters = value.chars(); + characters + .next() + .is_some_and(|first| first.is_ascii_lowercase()) + && value.len() <= max + && value.chars().all(|character| { + character.is_ascii_lowercase() || character.is_ascii_digit() || character == '_' + }) +} + +/// The handle of the kernel-built Speak entry. It is indexed in the same draft +/// index as world-declared entries, so a genesis subject grants it with an +/// ordinary `Ref::Draft` and there is no second grant path. +pub(super) const KERNEL_SPEAK_HANDLE: &str = "ghostlight.affordance.speak"; + +/// The grant every genesis subject carries: a draft reference to the +/// kernel-built entry, resolved by the ordinary handle index. World ingress and +/// every fixture name this rather than repeating the handle literal. +pub(super) fn kernel_speak_grant() -> BTreeSet> { + BTreeSet::from([Ref::Draft(DraftHandle::new(KERNEL_SPEAK_HANDLE))]) +} + +/// Zero roles, zero slots, one empty band, one utterance, and one audience: a +/// voice fills the room it is standing in. Zero roles is load-bearing — the +/// Interpreter lane submits no bindings and a consumer's speak payload carries +/// only +/// text. The precondition is not vacuous: an unplaced subject has no +/// co-location audience and fails with `NoAudience`. +pub(super) fn kernel_speak_entry() -> Affordance { + Affordance { + kind: AffordanceKindName("speak".into()), + roles: Vec::new(), + preconditions: vec![Precondition::CanBroadcast { + via: AudienceSpec::Colocated, + }], + effect_slots: Vec::new(), + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + carries_speech: true, + } +} + +/// Whether a stored catalog entry would still be admitted by the declaration +/// validator. One validator, two readers: the resolver rejects a bad entry, and +/// journal recovery refuses a store that already holds one. +pub(super) fn entry_is_admissible(entry: &Affordance) -> bool { + let mut mismatches = Vec::new(); + validate_affordance( + &DraftHandle::new(""), + &entry.kind, + &entry.roles, + &entry.preconditions, + &entry.effect_slots, + &entry.outcome_bands, + entry.carries_speech, + &mut mismatches, + ); + mismatches.is_empty() +} + +/// The catalog-entry resolver, beside `resolve_entity`/`_subject`/`_route`. An +/// entry carries no components, so there is nothing to check past namespace +/// agreement. +fn resolve_affordance( + site: Site, + reference: &Ref, + index: &BTreeMap, + catalog: &BTreeMap, + mismatches: &mut Vec, +) -> Option> { + match reference { + Ref::Draft(named) => match index.get(named) { + None => { + mismatches.push(Mismatch::UnresolvedDraft { + site, + referent: named.clone(), + expected: RefKind::Affordance, + }); + None + } + Some(kind) if *kind != RefKind::Affordance => { + mismatches.push(Mismatch::WrongKind { + site, + referent: RefName::Affordance(reference.clone()), + expected: RefKind::Affordance, + actual: *kind, + }); + None + } + Some(_) => Some(Key::Draft(named.clone())), + }, + Ref::Existing(affordance_id) => { + if catalog.contains_key(affordance_id) { + Some(Key::Existing(*affordance_id)) + } else { + mismatches.push(Mismatch::UnknownCanonical { + site, + expected: RefKind::Affordance, + }); + None + } + } + } +} + +/// The one validator of a catalog entry, run per declared entry in declaration +/// order inside the resolver's accumulate-then-gate loop. +fn validate_affordance( + handle: &DraftHandle, + kind: &AffordanceKindName, + roles: &[RoleSpec], + preconditions: &[Precondition], + effect_slots: &[EffectSlot], + outcome_bands: &[OutcomeBand], + carries_speech: bool, + mismatches: &mut Vec, +) { + let site = || Site::Declaration(handle.clone()); + if !is_tool_name(&kind.0, 48) || roles.iter().any(|spec| !is_tool_name(&spec.role.0, 32)) { + mismatches.push(Mismatch::InvalidAffordanceName { + handle: handle.clone(), + }); + } + let mut declared: BTreeMap = BTreeMap::new(); + for spec in roles { + if spec.role.0 == ACTOR_ROLE { + mismatches.push(Mismatch::ReservedRole { + handle: handle.clone(), + }); + } + match declared.entry(spec.role.clone()) { + Entry::Vacant(slot) => { + slot.insert(spec.kind); + } + Entry::Occupied(_) => mismatches.push(Mismatch::DuplicateRole { + handle: handle.clone(), + role: spec.role.clone(), + }), + } + // No `Target` names the catalog namespace, so a role of that kind could + // never be bound. + if spec.kind == RefKind::Affordance { + mismatches.push(Mismatch::RoleKindUnfit { + handle: handle.clone(), + role: spec.role.clone(), + }); + } + } + // The kernel binds `actor` to the acting subject, so preconditions and + // slots may name it like any role. + declared.insert(Role(ACTOR_ROLE.into()), ANY_SUBJECT); + let require = + |role: &Role, expected: RefKind, mismatches: &mut Vec| match declared.get(role) { + None => mismatches.push(Mismatch::UnknownRole { + handle: handle.clone(), + role: role.clone(), + }), + Some(actual) if *actual != expected => mismatches.push(Mismatch::RoleKindUnfit { + handle: handle.clone(), + role: role.clone(), + }), + Some(_) => {} + }; + let require_subject = |role: &Role, mismatches: &mut Vec| match declared.get(role) { + None => mismatches.push(Mismatch::UnknownRole { + handle: handle.clone(), + role: role.clone(), + }), + Some(RefKind::Subject(_)) => {} + Some(_) => mismatches.push(Mismatch::RoleKindUnfit { + handle: handle.clone(), + role: role.clone(), + }), + }; + let require_audience = |via: &AudienceSpec, mismatches: &mut Vec| match via { + AudienceSpec::Colocated => {} + AudienceSpec::Channel(role) => require(role, CHANNEL, mismatches), + }; + for precondition in preconditions { + match precondition { + Precondition::Present { at } => { + require(at, RefKind::Entity(EntityKind::Place), mismatches); + } + Precondition::Reachable { to, within } => { + require(to, RefKind::Entity(EntityKind::Place), mismatches); + if !is_valid_cost(*within) { + mismatches.push(Mismatch::InvalidCost { site: site() }); + } + } + Precondition::Holds { resource, .. } => { + require(resource, RefKind::Entity(EntityKind::Resource), mismatches); + } + Precondition::Authorized { over, kind } => { + // Jurisdiction runs over subjects, places, and routes. A + // resource, fact, or channel is covered by nothing, so a role + // of that kind is refused at declaration rather than always + // failing at invocation. + match declared.get(over) { + None => mismatches.push(Mismatch::UnknownRole { + handle: handle.clone(), + role: over.clone(), + }), + Some(RefKind::Subject(_)) | Some(&PLACE) | Some(&ROUTE) => {} + Some(_) => mismatches.push(Mismatch::RoleKindUnfit { + handle: handle.clone(), + role: over.clone(), + }), + } + if !is_civic_name(&kind.0) { + mismatches.push(Mismatch::InvalidCivicName { site: site() }); + } + } + Precondition::HasStanding { grievance } => { + if !is_civic_name(&grievance.0) { + mismatches.push(Mismatch::InvalidCivicName { site: site() }); + } + } + Precondition::Knows { fact, .. } => require(fact, FACT, mismatches), + Precondition::CanBroadcast { via } => require_audience(via, mismatches), + Precondition::CanReach { subject, via } => { + require_subject(subject, mismatches); + require_audience(via, mismatches); + } + Precondition::Committed { to, .. } => require_subject(to, mismatches), + } + } + // A speech-carrying entry must name exactly one audience: the lowering reads + // it, so none is unlowerable and two is unchoosable. + if carries_speech { + let audiences = preconditions + .iter() + .filter(|precondition| { + matches!( + precondition, + Precondition::CanBroadcast { .. } | Precondition::CanReach { .. } + ) + }) + .count(); + if audiences == 0 { + mismatches.push(Mismatch::SpeechWithoutAudience { + handle: handle.clone(), + }); + } else if audiences > 1 { + mismatches.push(Mismatch::AmbiguousSpeechAudience { + handle: handle.clone(), + }); + } + } + for (index, slot) in effect_slots.iter().enumerate() { + let arity = slot.op_kind.arity(); + if slot + .op_kind + .payload_names() + .iter() + .any(|name| !is_civic_name(name)) + { + mismatches.push(Mismatch::InvalidCivicName { site: site() }); + } + if slot.roles.len() != arity.len() { + mismatches.push(Mismatch::SlotRoleArity { + handle: handle.clone(), + slot: index, + }); + } + for (role, rule) in slot.roles.iter().zip(arity.iter()) { + match declared.get(role) { + None => mismatches.push(Mismatch::UnknownRole { + handle: handle.clone(), + role: role.clone(), + }), + Some(declared_kind) if !role_kind_fits(rule, *declared_kind) => { + mismatches.push(Mismatch::RoleKindUnfit { + handle: handle.clone(), + role: role.clone(), + }); + } + Some(_) => {} + } + } + let fits = match (slot.op_kind.dimension(), slot.bounds) { + (BoundsDimension::None, Bounds::None) => true, + (BoundsDimension::Quantity, Bounds::Quantity(ceiling)) => ceiling.0 >= 1, + (BoundsDimension::Cost, Bounds::Cost(ceiling)) => is_valid_cost(ceiling), + _ => false, + }; + if !fits { + mismatches.push(Mismatch::SlotBoundMismatch { + handle: handle.clone(), + slot: index, + }); + } + } + if outcome_bands.is_empty() { + mismatches.push(Mismatch::NoOutcomeBand { + handle: handle.clone(), + }); + } + for (index, band) in outcome_bands.iter().enumerate() { + if band.weight == 0 { + mismatches.push(Mismatch::ZeroBandWeight { + handle: handle.clone(), + band: index, + }); + } + if band.effects.iter().any(|slot| *slot >= effect_slots.len()) { + mismatches.push(Mismatch::DanglingBandEffect { + handle: handle.clone(), + band: index, + }); + } + if band.effects.windows(2).any(|pair| pair[0] >= pair[1]) { + mismatches.push(Mismatch::BandEffectsNotCanonical { + handle: handle.clone(), + band: index, + }); + } + } + if effect_slots.is_empty() && !carries_speech { + mismatches.push(Mismatch::InertAffordance { + handle: handle.clone(), + }); + } +} + +/// The one entity resolver. `expected` names the kind the referring site +/// requires; a handle or ID that answers with another kind is `WrongKind`. +fn resolve_entity( + site: Site, + expected_kind: EntityKind, + reference: &Ref, + index: &BTreeMap, + entities: &BTreeMap, + mismatches: &mut Vec, +) -> Option> { + let expected = RefKind::Entity(expected_kind); + match reference { + Ref::Draft(named) => match index.get(named) { + None => { + mismatches.push(Mismatch::UnresolvedDraft { + site, + referent: named.clone(), + expected, + }); + None + } + Some(kind) if *kind != expected => { + mismatches.push(Mismatch::WrongKind { + site, + referent: RefName::Entity(reference.clone()), + expected, + actual: *kind, + }); + None + } + Some(_) => Some(Key::Draft(named.clone())), + }, + Ref::Existing(entity_id) => match entities.get(entity_id) { + None => { + mismatches.push(Mismatch::UnknownCanonical { site, expected }); + None + } + Some(record) if record.kind != expected_kind => { + mismatches.push(Mismatch::WrongKind { + site, + referent: RefName::Entity(reference.clone()), + expected, + actual: RefKind::Entity(record.kind), + }); + None + } + Some(_) => Some(Key::Existing(*entity_id)), + }, + } +} + +fn resolve_subject( + site: Site, + reference: &Ref, + index: &BTreeMap, + subjects: &BTreeMap, + mismatches: &mut Vec, +) -> Option> { + match reference { + Ref::Draft(named) => match index.get(named) { + None => { + mismatches.push(Mismatch::UnresolvedDraft { + site, + referent: named.clone(), + expected: ANY_SUBJECT, + }); + None + } + Some(RefKind::Subject(_)) => Some(Key::Draft(named.clone())), + Some(kind) => { + mismatches.push(Mismatch::WrongKind { + site, + referent: RefName::Subject(reference.clone()), + expected: ANY_SUBJECT, + actual: *kind, + }); + None + } + }, + Ref::Existing(subject_id) => { + if subjects.contains_key(subject_id) { + Some(Key::Existing(*subject_id)) + } else { + mismatches.push(Mismatch::UnknownCanonical { + site, + expected: ANY_SUBJECT, + }); + None + } + } + } +} + +fn resolve_route( + site: Site, + reference: &Ref, + index: &BTreeMap, + edges: &BTreeMap, + mismatches: &mut Vec, +) -> Option> { + match reference { + Ref::Draft(named) => match index.get(named) { + None => { + mismatches.push(Mismatch::UnresolvedDraft { + site, + referent: named.clone(), + expected: ROUTE, + }); + None + } + Some(kind) if *kind != ROUTE => { + mismatches.push(Mismatch::WrongKind { + site, + referent: RefName::Edge(reference.clone()), + expected: ROUTE, + actual: *kind, + }); + None + } + Some(_) => Some(Key::Draft(named.clone())), + }, + Ref::Existing(edge_id) => { + if edges.contains_key(edge_id) { + Some(Key::Existing(*edge_id)) + } else { + mismatches.push(Mismatch::UnknownCanonical { + site, + expected: ROUTE, + }); + None + } + } + } +} + +fn resolve_dependency_target( + site: Site, + target: &DependencyRef, + index: &BTreeMap, + state: &super::WorldState, + mismatches: &mut Vec, +) -> Option { + match target { + DependencyRef::Resource(reference) => resolve_entity( + site, + EntityKind::Resource, + reference, + index, + &state.entities, + mismatches, + ) + .map(TargetKey::Resource), + DependencyRef::Route(reference) => { + resolve_route(site, reference, index, &state.edges, mismatches).map(TargetKey::Route) + } + DependencyRef::Subject(reference) => { + resolve_subject(site, reference, index, &state.subjects, mismatches) + .map(TargetKey::Subject) + } + } +} + +/// Whether any subject in the candidate graph holds two grants of one kind over +/// overlapping ground, from any combination of direct grant and office +/// delegation. +fn graph_overlaps( + authority: &BTreeMap, BTreeSet>, + selection: &BTreeMap<(Key, OfficeName), OfficeCandidate>, + containers: &BTreeMap, Key>, + retired: &BTreeSet>, +) -> bool { + let holders: BTreeSet<&Key> = authority + .keys() + .chain( + selection + .values() + .filter_map(|office| office.incumbent.as_ref()), + ) + .collect(); + holders.into_iter().any(|holder| { + let effective: Vec = + candidate_effective_authority(holder, authority, selection, retired) + .into_iter() + .collect(); + effective.iter().enumerate().any(|(index, one)| { + effective[index + 1..].iter().any(|other| { + one.kind == other.kind + && candidate_targets_overlap(&one.over, &other.over, containers) + }) + }) + }) +} + +/// The candidate kind of a subject reference: the declared kind for a handle +/// this patch introduces, the committed kind otherwise. +fn subject_kind_of( + key: &Key, + index: &BTreeMap, + state: &super::WorldState, +) -> Option { + match key { + Key::Existing(subject_id) => state.subjects.get(subject_id).map(|subject| subject.kind), + Key::Draft(handle) => match index.get(handle) { + Some(RefKind::Subject(kind)) => *kind, + _ => None, + }, + } +} + +/// The institution half of every office operation: one subject reference, one +/// canonical office name, and the kind check that keeps an institution's +/// operational organ and its person-shaped voice two subjects. +fn resolve_office_institution( + position: usize, + institution: &Ref, + office: &OfficeName, + index: &BTreeMap, + state: &super::WorldState, + mismatches: &mut Vec, +) -> Option> { + let named = is_civic_name(&office.0); + if !named { + mismatches.push(Mismatch::InvalidCivicName { + site: Site::Operation(position), + }); + } + let key = resolve_subject( + Site::Operation(position), + institution, + index, + &state.subjects, + mismatches, + )?; + if subject_kind_of(&key, index, state) != Some(SubjectKind::Institution) { + mismatches.push(Mismatch::OfficeOnNonInstitution { + operation: position, + }); + return None; + } + named.then_some(key) +} + +/// The one reach resolver: every member of a subject set, or one place. +fn resolve_reach( + site: Site, + reach: &ReachRef, + index: &BTreeMap, + state: &super::WorldState, + mismatches: &mut Vec, +) -> Option { + match reach { + ReachRef::Subjects(members) => { + let mut resolved = BTreeSet::new(); + let mut complete = true; + for reference in members { + match resolve_subject(site.clone(), reference, index, &state.subjects, mismatches) { + Some(key) => { + resolved.insert(key); + } + None => complete = false, + } + } + complete.then_some(ReachKey::Subjects(resolved)) + } + ReachRef::Place(reference) => resolve_entity( + site, + EntityKind::Place, + reference, + index, + &state.entities, + mismatches, + ) + .map(ReachKey::Place), + } +} + +/// A channel controller is optional, so "declared none" and "named one that did +/// not resolve" are two answers, not one. +fn resolve_controller( + site: Site, + controller: &Option>, + index: &BTreeMap, + state: &super::WorldState, + mismatches: &mut Vec, +) -> Option>> { + match controller { + None => Some(None), + Some(reference) => { + resolve_subject(site, reference, index, &state.subjects, mismatches).map(Some) + } + } +} + +fn resolve_audience( + site: Site, + audience: &AudienceRef, + index: &BTreeMap, + state: &super::WorldState, + mismatches: &mut Vec, +) -> Option { + match audience { + AudienceRef::Colocated => Some(AudienceKey::Colocated), + AudienceRef::Channel(reference) => resolve_entity( + site, + EntityKind::Channel, + reference, + index, + &state.entities, + mismatches, + ) + .map(AudienceKey::Channel), + } +} + +fn resolve_authority_target( + site: Site, + target: &AuthorityTargetRef, + index: &BTreeMap, + state: &super::WorldState, + mismatches: &mut Vec, +) -> Option { + match target { + AuthorityTargetRef::Subject(reference) => { + resolve_subject(site, reference, index, &state.subjects, mismatches) + .map(AuthorityTargetKey::Subject) + } + AuthorityTargetRef::PlaceSubtree(reference) => resolve_entity( + site, + EntityKind::Place, + reference, + index, + &state.entities, + mismatches, + ) + .map(AuthorityTargetKey::PlaceSubtree), + } +} + +/// What a holder holds in the candidate map. Absence is zero, at both levels. +fn candidate_held( + holdings: &BTreeMap<(Key, Key), Quantity>, + holder: &Key, + resource: &Key, +) -> u64 { + holdings + .get(&(holder.clone(), resource.clone())) + .map_or(0, |quantity| quantity.0) +} + +/// Zero removes the slot, so one representation of nothing survives the patch. +fn candidate_set( + holdings: &mut BTreeMap<(Key, Key), Quantity>, + holder: &Key, + resource: &Key, + value: u64, +) { + let slot = (holder.clone(), resource.clone()); + if value == 0 { + holdings.remove(&slot); + } else { + holdings.insert(slot, Quantity(value)); + } +} + +/// A bound grammar is the whole catalog: a kind it lacks, or a role signature +/// it does not carry, is refused. A world with no grammar is not checked. +fn check_against_grammar( + state: &super::WorldState, + handle: &DraftHandle, + kind: &AffordanceKindName, + roles: &[RoleSpec], + mismatches: &mut Vec, +) { + let Some(grammar) = &state.grammar else { + return; + }; + let handle = handle.clone(); + mismatches.extend(grammar.refusal(kind, roles).map(|refusal| match refusal { + GrammarRefusal::KindNotInGrammar => Mismatch::AffordanceKindNotInGrammar { handle }, + GrammarRefusal::RolesDisagree => Mismatch::AffordanceRolesDisagreeWithGrammar { handle }, + GrammarRefusal::SpeakNotConversation => { + Mismatch::SpeakRenderPathDisagreesWithGrammar { handle } + } + })); +} + +/// The one resolution owner for every admission lane: declarations, references, +/// topology admission, and operation preconditions. Every check runs against the +/// complete candidate graph — what the world already holds plus what this patch +/// declares — and the whole mismatch set closes before the first ID is minted. +pub(super) fn resolve_patch( + state: &super::WorldState, + command_id: CommandId, + patch: &WorldPatch, + scale_intent: Option<&WorldScaleIntentRef>, + lens_weights: Option<&LensWeights>, +) -> Result> { + let world_id = state.world_id; + let admits_human = super::admits_human(state.revision, &state.subjects); + let mut mismatches = Vec::new(); + let mut index: BTreeMap = BTreeMap::new(); + + // The kernel-built Speak entry enters the same index as a world-declared + // one, before the declaration loop, so a world reusing its handle collides + // as a duplicate handle rather than through a reserved-name check. + let speak_handle = DraftHandle::new(KERNEL_SPEAK_HANDLE); + if admits_human { + index.insert(speak_handle.clone(), RefKind::Affordance); + } + if admits_human { + // The kernel-built entry is held to the grammar like any declaration. + let speak = kernel_speak_entry(); + check_against_grammar(state, &speak_handle, &speak.kind, &speak.roles, &mut mismatches); + } + let mut kind_names: BTreeSet = state + .affordance_catalog + .values() + .map(|entry| entry.kind.clone()) + .collect(); + if admits_human { + kind_names.insert(kernel_speak_entry().kind); + } + + let held_keys = held_import_keys(state.subjects.values()); + let mut declared_keys: BTreeSet<&ImportKey> = BTreeSet::new(); + for (position, declaration) in patch.declarations.iter().enumerate() { + let (handle, label, kind) = match declaration { + Declaration::Subject(subject) => ( + &subject.handle, + Some(&subject.label), + RefKind::Subject(Some(subject.kind)), + ), + Declaration::Entity(entity) => ( + &entity.handle, + Some(&entity.label), + RefKind::Entity(entity.kind), + ), + Declaration::Route(route) => (&route.handle, Some(&route.label), ROUTE), + // A catalog entry's name is its `kind`, checked by the entry + // validator against the tool-name alphabet rather than against the + // label rule. + Declaration::Affordance(affordance) => (&affordance.handle, None, RefKind::Affordance), + Declaration::Fact(fact) => (&fact.handle, Some(&fact.label), FACT), + Declaration::Channel(channel) => (&channel.handle, Some(&channel.label), CHANNEL), + }; + let named = is_canonical_text(&handle.0); + if !named { + mismatches.push(Mismatch::EmptyHandle { position }); + } + if label.is_some_and(|label| !is_canonical_text(label)) { + mismatches.push(Mismatch::EmptyLabel { + handle: handle.clone(), + }); + } + if named { + match index.entry(handle.clone()) { + Entry::Vacant(slot) => { + slot.insert(kind); + } + Entry::Occupied(_) => mismatches.push(Mismatch::DuplicateHandle { + handle: handle.clone(), + }), + } + } + if let Declaration::Subject(subject) = declaration + && let Some(key) = &subject.import_key + { + let handle = subject.handle.clone(); + match import_key_fault(key, &held_keys, &mut declared_keys) { + Some(ImportKeyFault::Malformed) => { + mismatches.push(Mismatch::MalformedImportKey { handle }); + } + Some(ImportKeyFault::Held) => mismatches.push(Mismatch::ImportKeyHeld { handle }), + Some(ImportKeyFault::Duplicate) => { + mismatches.push(Mismatch::DuplicateImportKey { handle }); + } + None => {} + } + } + if let Declaration::Affordance(affordance) = declaration { + validate_affordance( + &affordance.handle, + &affordance.kind, + &affordance.roles, + &affordance.preconditions, + &affordance.effect_slots, + &affordance.outcome_bands, + affordance.carries_speech, + &mut mismatches, + ); + check_against_grammar( + state, + &affordance.handle, + &affordance.kind, + &affordance.roles, + &mut mismatches, + ); + if !kind_names.insert(affordance.kind.clone()) { + mismatches.push(Mismatch::DuplicateAffordanceKind { + handle: affordance.handle.clone(), + }); + } + } + if let Declaration::Entity(entity) = declaration + && matches!(entity.kind, EntityKind::Fact | EntityKind::Channel) + { + mismatches.push(Mismatch::PayloadEntityKind { + handle: handle.clone(), + }); + } + if let Declaration::Fact(fact) = declaration { + if !is_canonical_text(fact.statement.as_str()) { + mismatches.push(Mismatch::EmptyStatement { + handle: handle.clone(), + }); + } + // The same predicate `Admit` uses, moved into the declaration loop so + // one rule serves evidenced quantity and evidenced canon alike. + if let FactStandingRef::Canonical { evidence } = &fact.standing + && !(is_canonical_text(&evidence.0) && patch.evidence.contains(evidence)) + { + mismatches.push(Mismatch::FactWithoutEvidence { + handle: handle.clone(), + }); + } + } + if let Declaration::Subject(subject) = declaration { + // Both ways. A mirror receives no opportunity, so it may hold no + // affordance; every other controller must hold one. + if matches!(subject.controller, NewController::External { .. }) + != subject.affordances.is_empty() + { + mismatches.push(Mismatch::ControllerGrantMismatch { + site: Site::Declaration(handle.clone()), + }); + } + if let NewController::Human { principal } = &subject.controller + && (!admits_human || super::validate_principal(principal).is_err()) + { + mismatches.push(Mismatch::UnadmittedController { + handle: handle.clone(), + }); + } + } + } + + for (position, evidence) in patch.evidence.iter().enumerate() { + if !is_canonical_text(&evidence.0) { + mismatches.push(Mismatch::EmptyEvidence { position }); + } + } + + // The candidate graph: canonical topology plus everything this patch + // declares. Containment, endpoints, and preconditions all read it. + let mut containers: BTreeMap, Key> = state + .entities + .iter() + .filter_map(|(entity_id, record)| { + record + .container + .map(|container| (Key::Existing(*entity_id), Key::Existing(container))) + }) + .collect(); + let mut routes: BTreeMap, RouteCandidate> = state + .edges + .iter() + .map(|(edge_id, record)| { + let (from, to) = record.endpoints(); + ( + Key::Existing(*edge_id), + RouteCandidate { + from: Key::Existing(from), + to: Key::Existing(to), + access: record.access().clone(), + cost: record.cost(), + open: record.is_open(), + }, + ) + }) + .collect(); + let mut positions: BTreeMap, Key> = state + .positions + .iter() + .map(|(subject_id, position)| (Key::Existing(*subject_id), Key::Existing(position.place))) + .collect(); + let mut holdings: BTreeMap<(Key, Key), Quantity> = state + .holdings + .iter() + .flat_map(|(subject_id, held)| { + held.iter().map(move |(entity_id, quantity)| { + ( + (Key::Existing(*subject_id), Key::Existing(*entity_id)), + *quantity, + ) + }) + }) + .collect(); + let seeded_holdings = holdings.clone(); + let mut dependencies: BTreeSet<(Key, TargetKey)> = state + .dependencies + .iter() + .flat_map(|(subject_id, bound)| { + bound.iter().map(move |target| { + ( + Key::Existing(*subject_id), + match target { + DependencyTarget::Resource(id) => TargetKey::Resource(Key::Existing(*id)), + DependencyTarget::Route(id) => TargetKey::Route(Key::Existing(*id)), + DependencyTarget::Subject(id) => TargetKey::Subject(Key::Existing(*id)), + }, + ) + }) + }) + .collect(); + let mut authority: BTreeMap, BTreeSet> = state + .authority + .iter() + .map(|(subject_id, grants)| { + ( + Key::Existing(*subject_id), + grants.iter().map(grant_key_of).collect(), + ) + }) + .collect(); + let mut selection: BTreeMap<(Key, OfficeName), OfficeCandidate> = state + .selection + .iter() + .flat_map(|(institution, offices)| { + offices.iter().map(move |(name, office)| { + ( + (Key::Existing(*institution), name.clone()), + OfficeCandidate { + incumbent: office.incumbent.map(Key::Existing), + delegated: office.delegated.clone(), + }, + ) + }) + }) + .collect(); + let mut redress: BTreeMap, AuthorityTargetKey)> = state + .redress + .iter() + .map(|(grievance, forum)| { + ( + grievance.clone(), + (Key::Existing(forum.forum), target_key_of(forum.standing)), + ) + }) + .collect(); + let mut facts: BTreeMap, FactCandidate> = state + .facts + .iter() + .map(|(entity_id, record)| { + ( + Key::Existing(*entity_id), + match &record.standing { + FactStanding::Canonical { .. } => FactCandidate::Canonical, + FactStanding::Claimed { by } => FactCandidate::Claimed(Key::Existing(*by)), + FactStanding::Ruled => FactCandidate::Ruled, + }, + ) + }) + .collect(); + // `Retire` and the affordance grant operations read and write these three + // candidates. `retired` and `mirrors` seed from the committed + // `ControllerAssignment`, which the resolver otherwise never reads: a + // declared subject can only ever be a fresh, unretired controller (or a + // freshly declared mirror, added below), so drafts start out of both sets. + // `affordance_holdings` seeds from committed `affordance_grants` and is + // extended below for a subject this same patch declares. + let mut retired: BTreeSet> = state + .controller_assignments + .keys() + .filter(|scope| super::is_retired(state, scope.subject_id)) + .map(|scope| Key::Existing(scope.subject_id)) + .collect(); + let mut mirrors: BTreeSet> = state + .controller_assignments + .iter() + .filter(|(_, assignment)| { + matches!(assignment, ControllerAssignment::ExternallyControlled { .. }) + }) + .map(|(scope, _)| Key::Existing(scope.subject_id)) + .collect(); + // Tracked the same way as `mirrors`: seeded from the committed human + // controller, extended below for a subject this same patch declares as + // `NewController::Human`. `Retire` refuses a Draft-phase approver out of + // this set instead of relying solely on the apply-time re-check, which + // otherwise only catches a genesis patch that declares and retires the + // human in the same breath after `open_owner` has already committed. + let mut humans: BTreeSet> = state + .controller_assignments + .iter() + .filter(|(_, assignment)| assignment.human_principal().is_some()) + .map(|(scope, _)| Key::Existing(scope.subject_id)) + .collect(); + let mut affordance_holdings: BTreeMap, BTreeSet>> = state + .affordance_grants + .iter() + .map(|(scope, granted)| { + ( + Key::Existing(scope.subject_id), + granted.iter().map(|id| Key::Existing(*id)).collect(), + ) + }) + .collect(); + let mut channels: BTreeMap, ChannelCandidate> = state + .channels + .iter() + .map(|(entity_id, record)| { + ( + Key::Existing(*entity_id), + ChannelCandidate { + reach: match &record.reach { + Reach::Subjects(members) => { + ReachKey::Subjects(members.iter().copied().map(Key::Existing).collect()) + } + Reach::Place(place) => ReachKey::Place(Key::Existing(*place)), + }, + controller: record.controller.map(Key::Existing), + }, + ) + }) + .collect(); + // Keys and payload, so an `AcquireKnowledge` that changes nothing is + // `NoOperationEffect` before any ID is minted. `Witness` is modelled here + // too: its landing is a subtree of `positions`, both maps are candidate + // maps, and so the fan-out it will perform at apply is derivable now — a + // subject this patch relocated into the subtree counts, and a witness that + // reaches nobody is refused at resolve exactly as `apply_operation` + // refuses it. + // + // `Communicate` never enters, and the difference is not scale. A telling is + // an act whose occurrence does not depend on its reception: its empty + // fan-out is legal, so there is nothing for this map to refuse and no + // refusal for it to predict. A witnessed event is only its reception, so + // its landing is its legality. + // + // Neither operation can write `Told`. This map can represent a `Told` + // entry, but no `ComponentOp` can construct one: `AcquireKnowledge` takes + // an `AuthoredSource`, `Witness` takes no source at all, and neither type + // has a `Told` variant — + // `action::no_component_op_kind_lowers_to_a_told_knowledge_write` pins both + // lowering sites that could otherwise drift. If a future operation is ever + // given the power to write `Told` directly — bypassing `Communicate`'s own + // apply-time fan-out — it must model that fan-out into this candidate graph + // first, or `resolve_patch` will silently reason about a knowledge state + // the apply pass will not produce. + let mut knowledge: BTreeMap<(Key, Key), KnowledgeCandidate> = state + .knowledge + .iter() + .flat_map(|(subject_id, held)| { + held.iter().map(move |(fact, entry)| { + ( + (Key::Existing(*subject_id), Key::Existing(*fact)), + KnowledgeCandidate { + confidence: entry.confidence, + source: match entry.source { + KnowledgeSource::Witnessed => KnowledgeSourceKey::Witnessed, + KnowledgeSource::Evidenced => KnowledgeSourceKey::Evidenced, + KnowledgeSource::Told { by, via } => KnowledgeSourceKey::Told { + by: Key::Existing(by), + via: via.map(Key::Existing), + }, + KnowledgeSource::Seen { by } => KnowledgeSourceKey::Seen { + by: Key::Existing(by), + }, + }, + }, + ) + }) + }) + .collect(); + // Presence is all a discharge asks, and a create cannot collide: the key is + // command-derived and the index is unique within one patch. + let mut commitments: BTreeSet<(Key, CommitmentKey)> = state + .commitments + .iter() + .flat_map(|(subject_id, held)| { + held.keys() + .map(move |key| (Key::Existing(*subject_id), *key)) + }) + .collect(); + let mut pressures: BTreeMap<(Key, PressureSourceKey), u32> = state + .pressures + .iter() + .flat_map(|(target, held)| { + held.iter().map(move |(source, magnitude)| { + ( + ( + Key::Existing(*target), + match source { + PressureSource::Commitment { subject, key } => { + PressureSourceKey::Commitment { + subject: Key::Existing(*subject), + key: *key, + } + } + PressureSource::Dependency(DependencyTarget::Resource(entity_id)) => { + PressureSourceKey::Dependency(TargetKey::Resource(Key::Existing( + *entity_id, + ))) + } + PressureSource::Dependency(DependencyTarget::Route(edge_id)) => { + PressureSourceKey::Dependency(TargetKey::Route(Key::Existing( + *edge_id, + ))) + } + PressureSource::Dependency(DependencyTarget::Subject(subject_id)) => { + PressureSourceKey::Dependency(TargetKey::Subject(Key::Existing( + *subject_id, + ))) + } + PressureSource::Subject(subject_id) => { + PressureSourceKey::Subject(Key::Existing(*subject_id)) + } + }, + ), + magnitude.0, + ) + }) + }) + .collect(); + let mut deltas: BTreeMap, LedgerDelta> = BTreeMap::new(); + let mut declared_places: Vec<(DraftHandle, Key)> = Vec::new(); + + for declaration in &patch.declarations { + match declaration { + Declaration::Entity(entity) => { + if entity.kind == EntityKind::Place { + declared_places + .push((entity.handle.clone(), Key::Draft(entity.handle.clone()))); + } + if let Some(reference) = &entity.container { + if entity.kind != EntityKind::Place { + mismatches.push(Mismatch::WrongKind { + site: Site::Declaration(entity.handle.clone()), + referent: RefName::Entity(reference.clone()), + expected: PLACE, + actual: RefKind::Entity(entity.kind), + }); + } else if let Some(parent) = resolve_entity( + Site::Declaration(entity.handle.clone()), + EntityKind::Place, + reference, + &index, + &state.entities, + &mut mismatches, + ) { + containers.insert(Key::Draft(entity.handle.clone()), parent); + } + } + } + Declaration::Affordance(_) => {} + Declaration::Fact(fact) => { + let standing = match &fact.standing { + FactStandingRef::Canonical { .. } => Some(FactCandidate::Canonical), + FactStandingRef::Claimed { by } => resolve_subject( + Site::Declaration(fact.handle.clone()), + by, + &index, + &state.subjects, + &mut mismatches, + ) + .map(FactCandidate::Claimed), + FactStandingRef::Ruled => Some(FactCandidate::Ruled), + }; + if let Some(standing) = standing { + facts.insert(Key::Draft(fact.handle.clone()), standing); + } + } + Declaration::Channel(channel) => { + let reach = resolve_reach( + Site::Declaration(channel.handle.clone()), + &channel.reach, + &index, + state, + &mut mismatches, + ); + let controller = resolve_controller( + Site::Declaration(channel.handle.clone()), + &channel.controller, + &index, + state, + &mut mismatches, + ); + if let (Some(reach), Some(controller)) = (reach, controller) { + channels.insert( + Key::Draft(channel.handle.clone()), + ChannelCandidate { reach, controller }, + ); + } + } + Declaration::Subject(subject) => { + let mut granted = BTreeSet::new(); + for reference in &subject.affordances { + if let Some(affordance_key) = resolve_affordance( + Site::Declaration(subject.handle.clone()), + reference, + &index, + &state.affordance_catalog, + &mut mismatches, + ) { + granted.insert(affordance_key); + } + } + if !granted.is_empty() { + affordance_holdings.insert(Key::Draft(subject.handle.clone()), granted); + } + if matches!(subject.controller, NewController::External { .. }) { + mirrors.insert(Key::Draft(subject.handle.clone())); + } + if matches!(subject.controller, NewController::Human { .. }) { + humans.insert(Key::Draft(subject.handle.clone())); + } + if let Some(reference) = &subject.position + && let Some(place) = resolve_entity( + Site::Declaration(subject.handle.clone()), + EntityKind::Place, + reference, + &index, + &state.entities, + &mut mismatches, + ) + { + positions.insert(Key::Draft(subject.handle.clone()), place); + } + } + Declaration::Route(route) => { + let from = resolve_entity( + Site::Declaration(route.handle.clone()), + EntityKind::Place, + &route.from, + &index, + &state.entities, + &mut mismatches, + ); + let to = resolve_entity( + Site::Declaration(route.handle.clone()), + EntityKind::Place, + &route.to, + &index, + &state.entities, + &mut mismatches, + ); + if !is_valid_cost(route.cost) { + mismatches.push(Mismatch::InvalidCost { + site: Site::Declaration(route.handle.clone()), + }); + } + if let (Some(from), Some(to)) = (from, to) { + if from == to { + mismatches.push(Mismatch::RouteSelfLoop { + referent: route.handle.clone(), + }); + } + routes.insert( + Key::Draft(route.handle.clone()), + RouteCandidate { + from, + to, + access: route.access.clone(), + cost: route.cost, + open: true, + }, + ); + } + } + } + } + + // Containment acyclicity. Containment is immutable after admission and + // admission already refused cycles, so every cycle contains a declared + // place; walking from each declared place names them all. + for (handle, start) in &declared_places { + if contains_itself(start, &containers) { + mismatches.push(Mismatch::ContainmentCycle { + referent: handle.clone(), + }); + } + } + + for (position, operation) in patch.operations.iter().enumerate() { + let site = Site::Operation(position); + match operation { + ComponentOp::CreateCommitment { + subject, + counterparty, + kind, + due, + period, + checks, + statement, + } => { + if !is_canonical_text(statement.as_str()) { + mismatches.push(Mismatch::NoncanonicalText { + operation: position, + }); + } + let subject_key = resolve_subject( + site.clone(), + subject, + &index, + &state.subjects, + &mut mismatches, + ); + let counterparty_key = counterparty.as_ref().map(|reference| { + resolve_subject( + site.clone(), + reference, + &index, + &state.subjects, + &mut mismatches, + ) + }); + let mut checks_resolve = true; + for check in checks { + checks_resolve &= + resolve_check(site.clone(), check, &index, state, &mut mismatches); + } + if (*kind == CommitmentKind::Routine) != period.is_some() { + mismatches.push(Mismatch::CommitmentPeriodMismatch { + operation: position, + }); + } + if let Some(period) = period + && !is_valid_cost(Cost(period.minutes())) + { + mismatches.push(Mismatch::InvalidCost { site: site.clone() }); + } + if *kind != CommitmentKind::Routine && !checks.is_empty() { + mismatches.push(Mismatch::ChecksOnNonRoutine { + operation: position, + }); + } + // A promise cannot be born past due: it would press on its + // subject on the very next tick with no chance to act. + if *due <= state.now { + mismatches.push(Mismatch::CommitmentDueInThePast { + operation: position, + }); + } + if counterparty.is_some() && *kind == CommitmentKind::Goal { + mismatches.push(Mismatch::GoalWithCounterparty { + operation: position, + }); + } + let Some(subject_key) = subject_key else { + continue; + }; + // A retired subject cannot act, and making a promise is + // acting: refused here the same way `RetiredSubjectActed` + // refuses a retired office incumbent below. + if retired.contains(&subject_key) { + mismatches.push(Mismatch::RetiredSubjectActed { + operation: position, + }); + continue; + } + if let Some(counterparty_key) = &counterparty_key { + match counterparty_key { + None => continue, + Some(counterparty_key) if *counterparty_key == subject_key => { + mismatches.push(Mismatch::SelfCommitment { + operation: position, + }); + continue; + } + Some(_) => {} + } + } + if !checks_resolve { + continue; + } + commitments.insert(( + subject_key, + CommitmentKey { + command: command_id, + index: position as u32, + }, + )); + } + ComponentOp::DischargeCommitment { subject, key } => { + let Some(subject_key) = resolve_subject( + site.clone(), + subject, + &index, + &state.subjects, + &mut mismatches, + ) else { + continue; + }; + if !commitments.remove(&(subject_key, *key)) { + mismatches.push(Mismatch::UnknownCommitment { + operation: position, + }); + } + } + ComponentOp::AdvancePressure { source, target, by } + | ComponentOp::ReducePressure { source, target, by } => { + let advancing = matches!(operation, ComponentOp::AdvancePressure { .. }); + let target_key = resolve_subject( + site.clone(), + target, + &index, + &state.subjects, + &mut mismatches, + ); + let source_key = + resolve_pressure_source(site.clone(), source, &index, state, &mut mismatches); + let (Some(target_key), Some(source_key)) = (target_key, source_key) else { + continue; + }; + let slot = (target_key, source_key); + let current = pressures.get(&slot).copied().unwrap_or_default(); + let next = if advancing { + current.saturating_add(by.0) + } else { + current.saturating_sub(by.0) + }; + // A zero step and a subtraction that hits a floor both change + // nothing, which is one name and not three. + if next == current { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else if next == 0 { + pressures.remove(&slot); + } else { + pressures.insert(slot, next); + } + } + ComponentOp::ResolvePressure { source, target } => { + let target_key = resolve_subject( + site.clone(), + target, + &index, + &state.subjects, + &mut mismatches, + ); + let source_key = + resolve_pressure_source(site.clone(), source, &index, state, &mut mismatches); + let (Some(target_key), Some(source_key)) = (target_key, source_key) else { + continue; + }; + if pressures.remove(&(target_key, source_key)).is_none() { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } + } + ComponentOp::Relocate { subject, via } => { + let subject_key = resolve_subject( + Site::Operation(position), + subject, + &index, + &state.subjects, + &mut mismatches, + ); + let route_key = resolve_route( + Site::Operation(position), + via, + &index, + &state.edges, + &mut mismatches, + ); + let (Some(subject_key), Some(route_key)) = (subject_key, route_key) else { + continue; + }; + let Some(route) = routes.get(&route_key).cloned() else { + continue; + }; + let mut admitted = true; + match positions.get(&subject_key) { + None => { + mismatches.push(Mismatch::UnplacedSubject { + operation: position, + }); + admitted = false; + } + Some(place) if *place != route.from => { + mismatches.push(Mismatch::SubjectNotAtOrigin { + operation: position, + }); + admitted = false; + } + Some(_) => {} + } + if !route.open { + mismatches.push(Mismatch::RouteClosed { + operation: position, + }); + admitted = false; + } + // The resolver reads authority for the subject being moved, not + // for whoever proposed the patch, which is what keeps it + // actor-blind: the owner-admitted lane and the action lane get + // the same answer for the same move. A destination this patch + // declares is canonically unknown, so only a `Public` route + // reaches it. + let opened = match &route.to { + Key::Existing(destination) => route_admits( + state, + &canonical_grants(&candidate_effective_authority( + &subject_key, + &authority, + &selection, + &retired, + )), + &route.access, + *destination, + ), + Key::Draft(_) => route.access == AccessKind::Public, + }; + if !opened { + mismatches.push(Mismatch::RouteAccessRestricted { + operation: position, + }); + admitted = false; + } + if admitted { + positions.insert(subject_key, route.to); + } + } + ComponentOp::Retire { subject } => { + let Some(subject_key) = resolve_subject( + Site::Operation(position), + subject, + &index, + &state.subjects, + &mut mismatches, + ) else { + continue; + }; + if mirrors.contains(&subject_key) { + mismatches.push(Mismatch::RetiresAMirror { + operation: position, + }); + continue; + } + if retired.contains(&subject_key) { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + continue; + } + // A human's Draft approval cannot be removed by removing the + // human: `required_approvers` reads the live controller + // assignment and `Retired` carries no human principal, so an + // owner could otherwise retire the human, approve alone, and + // activate. Once the world is Active, approvals are frozen + // history judged by replay, and the human's subject may die. + // `humans` tracks a subject declared as `NewController::Human` + // in this same patch exactly as `mirrors` tracks a freshly + // declared mirror, so a genesis patch that declares and + // retires the human in one breath is refused here rather than + // only by the apply-time re-check after admission. + if state.phase == super::WorldPhase::Draft && humans.contains(&subject_key) { + mismatches.push(Mismatch::RetiresAnApprover { + operation: position, + }); + continue; + } + retired.insert(subject_key.clone()); + positions.remove(&subject_key); + affordance_holdings.remove(&subject_key); + } + ComponentOp::OpenRoute { route } | ComponentOp::CloseRoute { route } => { + let open = matches!(operation, ComponentOp::OpenRoute { .. }); + let Some(route_key) = resolve_route( + Site::Operation(position), + route, + &index, + &state.edges, + &mut mismatches, + ) else { + continue; + }; + let Some(candidate) = routes.get_mut(&route_key) else { + continue; + }; + if candidate.open == open { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + candidate.open = open; + } + } + ComponentOp::AlterCost { route, cost } => { + let route_key = resolve_route( + Site::Operation(position), + route, + &index, + &state.edges, + &mut mismatches, + ); + if !is_valid_cost(*cost) { + mismatches.push(Mismatch::InvalidCost { + site: Site::Operation(position), + }); + continue; + } + let Some(route_key) = route_key else { continue }; + let Some(candidate) = routes.get_mut(&route_key) else { + continue; + }; + if candidate.cost == *cost { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + candidate.cost = *cost; + } + } + ComponentOp::Transfer { + from, + to, + resource, + qty, + } => { + let from_key = resolve_subject( + Site::Operation(position), + from, + &index, + &state.subjects, + &mut mismatches, + ); + let to_key = resolve_subject( + Site::Operation(position), + to, + &index, + &state.subjects, + &mut mismatches, + ); + let resource_key = resolve_entity( + Site::Operation(position), + EntityKind::Resource, + resource, + &index, + &state.entities, + &mut mismatches, + ); + if qty.0 == 0 { + mismatches.push(Mismatch::ZeroQuantity { + operation: position, + }); + } + let (Some(from_key), Some(to_key), Some(resource_key)) = + (from_key, to_key, resource_key) + else { + continue; + }; + if from_key == to_key { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + continue; + } + if qty.0 == 0 { + continue; + } + let held = candidate_held(&holdings, &from_key, &resource_key); + let Some(remaining) = held.checked_sub(qty.0) else { + mismatches.push(Mismatch::InsufficientCustody { + operation: position, + }); + continue; + }; + let Some(credited) = + candidate_held(&holdings, &to_key, &resource_key).checked_add(qty.0) + else { + mismatches.push(Mismatch::QuantityOverflow { + operation: position, + }); + continue; + }; + candidate_set(&mut holdings, &from_key, &resource_key, remaining); + candidate_set(&mut holdings, &to_key, &resource_key, credited); + // A transfer contributes to no ledger term: the equation proves + // it, because moving a different amount out than in breaks the + // resource's total. + deltas.entry(resource_key).or_default(); + } + ComponentOp::Transform { + holder, + from_resource, + into_resource, + qty, + } => { + let holder_key = resolve_subject( + Site::Operation(position), + holder, + &index, + &state.subjects, + &mut mismatches, + ); + let from_key = resolve_entity( + Site::Operation(position), + EntityKind::Resource, + from_resource, + &index, + &state.entities, + &mut mismatches, + ); + let into_key = resolve_entity( + Site::Operation(position), + EntityKind::Resource, + into_resource, + &index, + &state.entities, + &mut mismatches, + ); + if qty.0 == 0 { + mismatches.push(Mismatch::ZeroQuantity { + operation: position, + }); + } + let (Some(holder_key), Some(from_key), Some(into_key)) = + (holder_key, from_key, into_key) + else { + continue; + }; + if from_key == into_key { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + continue; + } + if qty.0 == 0 { + continue; + } + let Some(remaining) = + candidate_held(&holdings, &holder_key, &from_key).checked_sub(qty.0) + else { + mismatches.push(Mismatch::InsufficientCustody { + operation: position, + }); + continue; + }; + let Some(gained) = + candidate_held(&holdings, &holder_key, &into_key).checked_add(qty.0) + else { + mismatches.push(Mismatch::QuantityOverflow { + operation: position, + }); + continue; + }; + candidate_set(&mut holdings, &holder_key, &from_key, remaining); + candidate_set(&mut holdings, &holder_key, &into_key, gained); + deltas.entry(from_key).or_default().spent += u128::from(qty.0); + deltas.entry(into_key).or_default().gained += u128::from(qty.0); + } + ComponentOp::Consume { + holder, + resource, + qty, + } => { + let holder_key = resolve_subject( + Site::Operation(position), + holder, + &index, + &state.subjects, + &mut mismatches, + ); + let resource_key = resolve_entity( + Site::Operation(position), + EntityKind::Resource, + resource, + &index, + &state.entities, + &mut mismatches, + ); + if qty.0 == 0 { + mismatches.push(Mismatch::ZeroQuantity { + operation: position, + }); + } + let (Some(holder_key), Some(resource_key)) = (holder_key, resource_key) else { + continue; + }; + if qty.0 == 0 { + continue; + } + let Some(remaining) = + candidate_held(&holdings, &holder_key, &resource_key).checked_sub(qty.0) + else { + mismatches.push(Mismatch::InsufficientCustody { + operation: position, + }); + continue; + }; + candidate_set(&mut holdings, &holder_key, &resource_key, remaining); + deltas.entry(resource_key).or_default().consumed += u128::from(qty.0); + } + ComponentOp::Admit { + holder, + resource, + qty, + evidence, + } => { + let holder_key = resolve_subject( + Site::Operation(position), + holder, + &index, + &state.subjects, + &mut mismatches, + ); + let resource_key = resolve_entity( + Site::Operation(position), + EntityKind::Resource, + resource, + &index, + &state.entities, + &mut mismatches, + ); + if qty.0 == 0 { + mismatches.push(Mismatch::ZeroQuantity { + operation: position, + }); + } + let evidenced = is_canonical_text(&evidence.0) && patch.evidence.contains(evidence); + if !evidenced { + mismatches.push(Mismatch::AdmitWithoutEvidence { + operation: position, + }); + } + let (Some(holder_key), Some(resource_key)) = (holder_key, resource_key) else { + continue; + }; + if qty.0 == 0 || !evidenced { + continue; + } + let Some(admitted) = + candidate_held(&holdings, &holder_key, &resource_key).checked_add(qty.0) + else { + mismatches.push(Mismatch::QuantityOverflow { + operation: position, + }); + continue; + }; + candidate_set(&mut holdings, &holder_key, &resource_key, admitted); + deltas.entry(resource_key).or_default().admitted += u128::from(qty.0); + } + ComponentOp::Mint { + holder, + resource, + qty, + } => { + let holder_key = resolve_subject( + Site::Operation(position), + holder, + &index, + &state.subjects, + &mut mismatches, + ); + let resource_key = resolve_entity( + Site::Operation(position), + EntityKind::Resource, + resource, + &index, + &state.entities, + &mut mismatches, + ); + if qty.0 == 0 { + mismatches.push(Mismatch::ZeroQuantity { + operation: position, + }); + } + let (Some(holder_key), Some(resource_key)) = (holder_key, resource_key) else { + continue; + }; + if qty.0 == 0 { + continue; + } + let Some(minted) = + candidate_held(&holdings, &holder_key, &resource_key).checked_add(qty.0) + else { + mismatches.push(Mismatch::QuantityOverflow { + operation: position, + }); + continue; + }; + candidate_set(&mut holdings, &holder_key, &resource_key, minted); + deltas.entry(resource_key).or_default().admitted += u128::from(qty.0); + } + ComponentOp::Bind { subject, target } | ComponentOp::Release { subject, target } => { + let bind = matches!(operation, ComponentOp::Bind { .. }); + let subject_key = resolve_subject( + Site::Operation(position), + subject, + &index, + &state.subjects, + &mut mismatches, + ); + let target_key = resolve_dependency_target( + Site::Operation(position), + target, + &index, + state, + &mut mismatches, + ); + let (Some(subject_key), Some(target_key)) = (subject_key, target_key) else { + continue; + }; + if target_key == TargetKey::Subject(subject_key.clone()) { + mismatches.push(Mismatch::SelfDependency { + operation: position, + }); + continue; + } + let slot = (subject_key, target_key); + if dependencies.contains(&slot) == bind { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else if bind { + dependencies.insert(slot); + } else { + dependencies.remove(&slot); + } + } + ComponentOp::GrantAuthority { holder, grant } + | ComponentOp::RevokeAuthority { holder, grant } => { + let granting = matches!(operation, ComponentOp::GrantAuthority { .. }); + let holder_key = resolve_subject( + Site::Operation(position), + holder, + &index, + &state.subjects, + &mut mismatches, + ); + if !is_civic_name(&grant.kind.0) { + mismatches.push(Mismatch::InvalidCivicName { + site: Site::Operation(position), + }); + } + let over = resolve_authority_target( + Site::Operation(position), + &grant.over, + &index, + state, + &mut mismatches, + ); + let (Some(holder_key), Some(over)) = (holder_key, over) else { + continue; + }; + let entry = GrantKey { + kind: grant.kind.clone(), + over, + }; + // Admission-time only: a `Subject` grant landing inside a + // `PlaceSubtree` grant the holder already has, or the reverse, + // is a second source for the same kind of act. This does not + // reach `targets_overlap`/`verify_state_shape`, which stay + // structural and position-independent; a later `Relocate` + // that creates this shape is not re-derived as a violation. + if granting + && authority.get(&holder_key).is_some_and(|grants| { + grants.iter().any(|other| { + other.kind == entry.kind + && grant_targets_nest(state, &entry.over, &other.over) + }) + }) + { + mismatches.push(Mismatch::OverlappingJurisdiction { + operation: position, + }); + continue; + } + let held = authority + .get(&holder_key) + .is_some_and(|grants| grants.contains(&entry)); + if held == granting { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else if granting { + authority.entry(holder_key).or_default().insert(entry); + } else { + let empty = if let Some(grants) = authority.get_mut(&holder_key) { + grants.remove(&entry); + grants.is_empty() + } else { + false + }; + if empty { + authority.remove(&holder_key); + } + } + } + ComponentOp::GrantAffordance { subject, affordance } + | ComponentOp::RevokeAffordance { subject, affordance } => { + let granting = matches!(operation, ComponentOp::GrantAffordance { .. }); + let subject_key = resolve_subject( + Site::Operation(position), + subject, + &index, + &state.subjects, + &mut mismatches, + ); + let affordance_key = resolve_affordance( + Site::Operation(position), + affordance, + &index, + &state.affordance_catalog, + &mut mismatches, + ); + let (Some(subject_key), Some(affordance_key)) = (subject_key, affordance_key) + else { + continue; + }; + // A grant is authority over the catalog, not structure over + // ground: retirement and a mirror both hold no grant a patch + // may touch, whatever confinement later decides. + if retired.contains(&subject_key) || mirrors.contains(&subject_key) { + mismatches.push(Mismatch::GrantsOutsideControl { + operation: position, + }); + continue; + } + let held = affordance_holdings + .get(&subject_key) + .is_some_and(|granted| granted.contains(&affordance_key)); + if held == granting { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + continue; + } + if granting { + affordance_holdings + .entry(subject_key) + .or_default() + .insert(affordance_key); + } else { + let granted = affordance_holdings.entry(subject_key).or_default(); + if granted.len() == 1 { + mismatches.push(Mismatch::WouldLeaveSubjectMute { + operation: position, + }); + continue; + } + granted.remove(&affordance_key); + } + } + ComponentOp::OpenOffice { + institution, + office, + delegated, + } => { + let institution_key = resolve_office_institution( + position, + institution, + office, + &index, + state, + &mut mismatches, + ); + if delegated.is_empty() { + mismatches.push(Mismatch::EmptyDelegation { + operation: position, + }); + } + if delegated.iter().any(|kind| !is_civic_name(&kind.0)) { + mismatches.push(Mismatch::InvalidCivicName { + site: Site::Operation(position), + }); + } + let Some(institution_key) = institution_key else { + continue; + }; + if delegated.is_empty() { + continue; + } + let slot = (institution_key, office.clone()); + let incumbent = selection + .get(&slot) + .and_then(|current| current.incumbent.clone()); + if selection + .get(&slot) + .is_some_and(|current| ¤t.delegated == delegated) + { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + selection.insert( + slot, + OfficeCandidate { + incumbent, + delegated: delegated.clone(), + }, + ); + } + } + ComponentOp::CloseOffice { + institution, + office, + } + | ComponentOp::VacateOffice { + institution, + office, + } => { + let closing = matches!(operation, ComponentOp::CloseOffice { .. }); + let Some(institution_key) = resolve_office_institution( + position, + institution, + office, + &index, + state, + &mut mismatches, + ) else { + continue; + }; + let slot = (institution_key, office.clone()); + let Some(current) = selection.get(&slot).cloned() else { + mismatches.push(Mismatch::UnknownOffice { + operation: position, + }); + continue; + }; + if closing { + selection.remove(&slot); + } else if current.incumbent.is_none() { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + selection.insert( + slot, + OfficeCandidate { + incumbent: None, + ..current + }, + ); + } + } + ComponentOp::InstallIncumbent { + institution, + office, + incumbent, + } => { + let institution_key = resolve_office_institution( + position, + institution, + office, + &index, + state, + &mut mismatches, + ); + let incumbent_key = resolve_subject( + Site::Operation(position), + incumbent, + &index, + &state.subjects, + &mut mismatches, + ); + if let Some(incumbent_key) = &incumbent_key + && subject_kind_of(incumbent_key, &index, state) != Some(SubjectKind::Person) + { + mismatches.push(Mismatch::OfficeHolderNotPerson { + operation: position, + }); + continue; + } + let (Some(institution_key), Some(incumbent_key)) = (institution_key, incumbent_key) + else { + continue; + }; + if retired.contains(&incumbent_key) { + mismatches.push(Mismatch::RetiredSubjectActed { + operation: position, + }); + continue; + } + let slot = (institution_key.clone(), office.clone()); + let Some(current) = selection.get(&slot).cloned() else { + mismatches.push(Mismatch::UnknownOffice { + operation: position, + }); + continue; + }; + if selection.iter().any(|((held_by, name), other)| { + *held_by == institution_key + && name != office + && other.incumbent.as_ref() == Some(&incumbent_key) + }) { + mismatches.push(Mismatch::DuplicateIncumbency { + operation: position, + }); + continue; + } + if current.incumbent.as_ref() == Some(&incumbent_key) { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + selection.insert( + slot, + OfficeCandidate { + incumbent: Some(incumbent_key), + ..current + }, + ); + } + } + ComponentOp::OpenForum { + grievance, + forum, + standing, + } => { + if !is_civic_name(&grievance.0) { + mismatches.push(Mismatch::InvalidCivicName { + site: Site::Operation(position), + }); + } + let forum_key = resolve_subject( + Site::Operation(position), + forum, + &index, + &state.subjects, + &mut mismatches, + ); + let standing_key = resolve_authority_target( + Site::Operation(position), + standing, + &index, + state, + &mut mismatches, + ); + let (Some(forum_key), Some(standing_key)) = (forum_key, standing_key) else { + continue; + }; + if redress.get(grievance) == Some(&(forum_key.clone(), standing_key.clone())) { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + redress.insert(grievance.clone(), (forum_key, standing_key)); + } + } + ComponentOp::CloseForum { grievance } => { + if redress.remove(grievance).is_none() { + mismatches.push(Mismatch::UnknownForum { + operation: position, + }); + } + } + ComponentOp::AcquireKnowledge { + subject, + fact, + source, + confidence, + } => { + let subject_key = resolve_subject( + Site::Operation(position), + subject, + &index, + &state.subjects, + &mut mismatches, + ); + let fact_key = resolve_entity( + Site::Operation(position), + EntityKind::Fact, + fact, + &index, + &state.entities, + &mut mismatches, + ); + let (Some(subject_key), Some(fact_key)) = (subject_key, fact_key) else { + continue; + }; + if retired.contains(&subject_key) { + mismatches.push(Mismatch::RetiredSubjectActed { + operation: position, + }); + continue; + } + // Evidenced knowledge is knowledge of canon. A receipt cannot + // vouch for an assertion the kernel never evaluated. + if *source == AuthoredSource::Evidenced + && facts.get(&fact_key) != Some(&FactCandidate::Canonical) + { + mismatches.push(Mismatch::EvidencedKnowledgeOfClaim { + operation: position, + }); + continue; + } + let entry = KnowledgeCandidate { + confidence: *confidence, + source: match source { + AuthoredSource::Witnessed => KnowledgeSourceKey::Witnessed, + AuthoredSource::Evidenced => KnowledgeSourceKey::Evidenced, + }, + }; + let slot = (subject_key, fact_key); + if knowledge.get(&slot) == Some(&entry) { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + knowledge.insert(slot, entry); + } + } + ComponentOp::Forget { subject, fact } => { + let subject_key = resolve_subject( + Site::Operation(position), + subject, + &index, + &state.subjects, + &mut mismatches, + ); + let fact_key = resolve_entity( + Site::Operation(position), + EntityKind::Fact, + fact, + &index, + &state.entities, + &mut mismatches, + ); + let (Some(subject_key), Some(fact_key)) = (subject_key, fact_key) else { + continue; + }; + if retired.contains(&subject_key) { + mismatches.push(Mismatch::RetiredSubjectActed { + operation: position, + }); + continue; + } + if knowledge.remove(&(subject_key, fact_key)).is_none() { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } + } + ComponentOp::Communicate { speaker, fact, to } => { + let speaker_key = resolve_subject( + Site::Operation(position), + speaker, + &index, + &state.subjects, + &mut mismatches, + ); + let fact_key = resolve_entity( + Site::Operation(position), + EntityKind::Fact, + fact, + &index, + &state.entities, + &mut mismatches, + ); + let audience = resolve_audience( + Site::Operation(position), + to, + &index, + state, + &mut mismatches, + ); + let (Some(speaker_key), Some(_), Some(audience)) = + (speaker_key, fact_key, audience) + else { + continue; + }; + if retired.contains(&speaker_key) { + mismatches.push(Mismatch::RetiredSubjectActed { + operation: position, + }); + continue; + } + // Ontology admission: communication reaches only subjects inside + // the channel's reach, and a speaker outside it is not speaking. + if !candidate_in_audience( + &speaker_key, + &audience, + &speaker_key, + &positions, + &channels, + &containers, + ) { + mismatches.push(Mismatch::SpeakerOutsideAudience { + operation: position, + }); + } + } + ComponentOp::Witness { + fact, + place, + confidence, + } => { + let fact_key = resolve_entity( + Site::Operation(position), + EntityKind::Fact, + fact, + &index, + &state.entities, + &mut mismatches, + ); + let place_key = resolve_entity( + Site::Operation(position), + EntityKind::Place, + place, + &index, + &state.entities, + &mut mismatches, + ); + let (Some(fact_key), Some(place_key)) = (fact_key, place_key) else { + continue; + }; + // The apply-time fan-out, modelled: every candidate subject + // standing under the place — canonical positions plus this + // patch's own declarations and its own relocations, which + // earlier arms have already written into `positions` — less + // everyone this map already has holding the fact, which is the + // same "already a knower" test `unheld` applies over committed + // state. + let entry = KnowledgeCandidate { + confidence: *confidence, + source: KnowledgeSourceKey::Witnessed, + }; + let recipients: Vec> = positions + .iter() + .filter(|(subject_key, standing)| { + key_covers_place(&place_key, standing, &containers) + && !knowledge.contains_key(&((*subject_key).clone(), fact_key.clone())) + }) + .map(|(subject_key, _)| (*subject_key).clone()) + .collect(); + if recipients.is_empty() { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + for subject_key in recipients { + knowledge.insert((subject_key, fact_key.clone()), entry.clone()); + } + } + } + ComponentOp::SetPersonaMaterial { + subject, + values, + voice, + memories, + reads, + } => { + let site = Site::Operation(position); + let subject_key = + resolve_subject(site.clone(), subject, &index, &state.subjects, &mut mismatches); + let mut read_keys = Vec::with_capacity(reads.len()); + for read in reads { + read_keys.push(resolve_subject( + site.clone(), + &read.subject, + &index, + &state.subjects, + &mut mismatches, + )); + } + let texts = values + .iter() + .chain(memories.iter()) + .chain(std::iter::once(voice)) + .chain(reads.iter().map(|read| &read.statement)); + let mut read_subjects: BTreeSet<&Ref> = BTreeSet::new(); + let duplicate_read = reads.iter().any(|read| !read_subjects.insert(&read.subject)); + if texts.clone().any(|text| !is_canonical_text(text.as_str())) || duplicate_read { + mismatches.push(Mismatch::NoncanonicalText { + operation: position, + }); + } + let (Some(Key::Existing(subject_id)), true) = + (subject_key, read_keys.iter().all(Option::is_some)) + else { + continue; + }; + // Identical material on an existing subject changes nothing. A + // draft read can never equal a held one, so it is skipped here. + let held: Option> = read_keys + .iter() + .zip(reads) + .map(|(key, read)| match key { + Some(Key::Existing(id)) => Some((*id, read.statement.clone())), + _ => None, + }) + .collect(); + if let Some(held) = held + && state.persona_material.get(&subject_id) + == Some(&PersonaMaterial { + values: values.clone(), + voice: voice.clone(), + memories: memories.clone(), + reads: held, + }) + { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } + } + ComponentOp::SetReach { channel, reach } => { + let channel_key = resolve_entity( + Site::Operation(position), + EntityKind::Channel, + channel, + &index, + &state.entities, + &mut mismatches, + ); + let reach_key = resolve_reach( + Site::Operation(position), + reach, + &index, + state, + &mut mismatches, + ); + let (Some(channel_key), Some(reach_key)) = (channel_key, reach_key) else { + continue; + }; + let Some(candidate) = channels.get_mut(&channel_key) else { + continue; + }; + if candidate.reach == reach_key { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + candidate.reach = reach_key; + } + } + ComponentOp::SetController { + channel, + controller, + } => { + let channel_key = resolve_entity( + Site::Operation(position), + EntityKind::Channel, + channel, + &index, + &state.entities, + &mut mismatches, + ); + let controller_key = resolve_controller( + Site::Operation(position), + controller, + &index, + state, + &mut mismatches, + ); + let (Some(channel_key), Some(controller_key)) = (channel_key, controller_key) + else { + continue; + }; + let Some(candidate) = channels.get_mut(&channel_key) else { + continue; + }; + if candidate.controller == controller_key { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + candidate.controller = controller_key; + } + } + } + // Disjointness, checked against the complete candidate graph after each + // operation that could widen someone's jurisdiction, so two operations + // in one patch collide with each other and the failure names the one + // that created the collision. Only three operations can: a new grant, a + // widened office, and a new incumbency. + if matches!( + operation, + ComponentOp::GrantAuthority { .. } + | ComponentOp::OpenOffice { .. } + | ComponentOp::InstallIncumbent { .. } + ) && graph_overlaps(&authority, &selection, &containers, &retired) + { + mismatches.push(Mismatch::OverlappingJurisdiction { + operation: position, + }); + } + } + + // Conservation, over the complete candidate after every operation has been + // applied in order. Never per operation: a patch whose operations + // individually balance but whose net does not is impossible, and an + // intermediate negative was already caught above as `InsufficientCustody`. + for (resource_key, delta) in &mut deltas { + delta.before = seeded_holdings + .iter() + .filter(|((_, resource), _)| resource == resource_key) + .map(|(_, quantity)| u128::from(quantity.0)) + .sum(); + delta.after = holdings + .iter() + .filter(|((_, resource), _)| resource == resource_key) + .map(|(_, quantity)| u128::from(quantity.0)) + .sum(); + } + if let Some(resource) = check_ledger(&deltas) { + mismatches.push(Mismatch::CustodyNotConserved { + resource: RefName::Entity(match resource { + Key::Existing(entity_id) => Ref::Existing(entity_id), + Key::Draft(handle) => Ref::Draft(handle), + }), + }); + } + + if let Some(intent) = scale_intent { + for handle in intent.jurisdictions.keys() { + if index.get(handle) != Some(&PLACE) { + mismatches.push(Mismatch::UnknownJurisdictionRoot { + handle: handle.clone(), + }); + } + } + // Weights distribute the target and never raise it. + if intent + .jurisdictions + .values() + .map(|weight| u64::from(*weight)) + .sum::() + > 1000 + { + mismatches.push(Mismatch::ScaleWeightsExceedWhole); + } + } + + if let Some(weights) = lens_weights + && !weights.draws() + { + mismatches.push(Mismatch::LensWeightsNeverDraw); + } + + if patch.declarations.is_empty() && patch.operations.is_empty() { + mismatches.push(Mismatch::NoCanonicalChange); + } + + if admits_human + && !patch + .declarations + .iter() + .any(|declaration| matches!(declaration, Declaration::Subject(_))) + { + mismatches.push(Mismatch::NoDecisionSubject); + } + + if !mismatches.is_empty() { + mismatches.sort(); + return Err(mismatches); + } + + // No canonical ID exists above this line. Allocation starts only now. + let mut collisions = Vec::new(); + let mut entities = Vec::new(); + let mut allocated_entities: BTreeMap = BTreeMap::new(); + for declaration in &patch.declarations { + let Declaration::Entity(entity) = declaration else { + continue; + }; + let entity_id = EntityId(derive_id( + ENTITY_NAMESPACE, + world_id, + command_id, + &entity.handle, + None, + )); + if state.entities.contains_key(&entity_id) { + collisions.push(Mismatch::CanonicalCollision { + handle: entity.handle.clone(), + }); + } + allocated_entities.insert(entity.handle.clone(), entity_id); + entities.push(ResolvedEntity { + handle: entity.handle.clone(), + entity_id, + entity: EntityRecord { + label: entity.label.clone(), + kind: entity.kind, + container: None, + }, + }); + } + // Facts and channels allocate through the same entity namespace and the same + // `derive_id`, so no namespace is added and `RefKind::Entity` types every + // reference to one. They stay out of `entities` above so that vector remains + // a zip over the place and resource declarations. + for declaration in &patch.declarations { + let handle = match declaration { + Declaration::Fact(fact) => &fact.handle, + Declaration::Channel(channel) => &channel.handle, + _ => continue, + }; + let entity_id = EntityId(derive_id( + ENTITY_NAMESPACE, + world_id, + command_id, + handle, + None, + )); + if state.entities.contains_key(&entity_id) { + collisions.push(Mismatch::CanonicalCollision { + handle: handle.clone(), + }); + } + allocated_entities.insert(handle.clone(), entity_id); + } + let entity_id_of = |key: &Key| -> EntityId { + match key { + Key::Existing(entity_id) => *entity_id, + Key::Draft(handle) => *allocated_entities + .get(handle) + .expect("a draft entity reference resolved above"), + } + }; + for (resolved, declaration) in entities + .iter_mut() + .zip( + patch + .declarations + .iter() + .filter_map(|declaration| match declaration { + Declaration::Entity(entity) => Some(entity), + _ => None, + }), + ) + { + resolved.entity.container = declaration + .container + .as_ref() + .map(|reference| entity_id_of(&key_of(reference))); + } + + let mut allocated_routes: BTreeMap = BTreeMap::new(); + let mut routes = Vec::new(); + for declaration in &patch.declarations { + let Declaration::Route(route) = declaration else { + continue; + }; + let edge_id = EdgeId(derive_id( + EDGE_NAMESPACE, + world_id, + command_id, + &route.handle, + None, + )); + if state.edges.contains_key(&edge_id) { + collisions.push(Mismatch::CanonicalCollision { + handle: route.handle.clone(), + }); + } + allocated_routes.insert(route.handle.clone(), edge_id); + routes.push(ResolvedRoute { + handle: route.handle.clone(), + edge_id, + edge: EdgeRecord::Route { + label: route.label.clone(), + from: entity_id_of(&key_of(&route.from)), + to: entity_id_of(&key_of(&route.to)), + access: route.access.clone(), + cost: route.cost, + open: true, + }, + }); + } + + let mut allocated_affordances: BTreeMap = BTreeMap::new(); + let mut affordances = Vec::new(); + let allocate_affordance = |handle: &DraftHandle, + entry: Affordance, + affordances: &mut Vec, + allocated: &mut BTreeMap, + collisions: &mut Vec| { + let affordance_id = AffordanceId(derive_id( + AFFORDANCE_NAMESPACE, + world_id, + command_id, + handle, + None, + )); + if state.affordance_catalog.contains_key(&affordance_id) { + collisions.push(Mismatch::CanonicalCollision { + handle: handle.clone(), + }); + } + allocated.insert(handle.clone(), affordance_id); + affordances.push(ResolvedAffordance { + handle: handle.clone(), + affordance_id, + affordance: entry, + }); + }; + if admits_human { + allocate_affordance( + &speak_handle, + kernel_speak_entry(), + &mut affordances, + &mut allocated_affordances, + &mut collisions, + ); + } + for declaration in &patch.declarations { + let Declaration::Affordance(input) = declaration else { + continue; + }; + allocate_affordance( + &input.handle, + Affordance { + kind: input.kind.clone(), + roles: input.roles.clone(), + preconditions: input.preconditions.clone(), + effect_slots: input.effect_slots.clone(), + outcome_bands: input.outcome_bands.clone(), + carries_speech: input.carries_speech, + }, + &mut affordances, + &mut allocated_affordances, + &mut collisions, + ); + } + let affordance_id_of = |key: &Key| -> AffordanceId { + match key { + Key::Existing(affordance_id) => *affordance_id, + Key::Draft(handle) => *allocated_affordances + .get(handle) + .expect("a draft affordance reference resolved above"), + } + }; + + let mut allocated_subjects: BTreeMap = BTreeMap::new(); + let mut subjects = Vec::new(); + for declaration in &patch.declarations { + let Declaration::Subject(input) = declaration else { + continue; + }; + let subject_id = SubjectId(derive_id( + SUBJECT_NAMESPACE, + world_id, + command_id, + &input.handle, + None, + )); + if state.subjects.contains_key(&subject_id) { + collisions.push(Mismatch::CanonicalCollision { + handle: input.handle.clone(), + }); + } + allocated_subjects.insert(input.handle.clone(), subject_id); + let mut controller_id = || { + ControllerId(derive_id( + CONTROLLER_NAMESPACE, + world_id, + command_id, + &input.handle, + None, + )) + }; + let controller = match input.controller.clone() { + NewController::Human { principal } => ControllerAssignment::Human { + controller_id: controller_id(), + principal, + }, + NewController::NarrativePersona => ControllerAssignment::NarrativePersona { + controller_id: controller_id(), + }, + NewController::OperationalAgent => ControllerAssignment::OperationalAgent { + controller_id: controller_id(), + }, + // No controller id is derived, because there is no controller. + NewController::External { consumer } => { + ControllerAssignment::ExternallyControlled { consumer } + } + }; + let granted = input + .affordances + .iter() + .map(|reference| affordance_id_of(&key_of(reference))) + .collect(); + subjects.push(ResolvedSubject { + handle: input.handle.clone(), + subject_id, + subject: SubjectState { + label: input.label.clone(), + kind: input.kind, + import_key: input.import_key.clone(), + }, + controller, + affordances: granted, + position: input.position.as_ref().map(|reference| Position { + place: entity_id_of(&key_of(reference)), + }), + }); + } + + let subject_id_of = |key: &Key| -> SubjectId { + match key { + Key::Existing(subject_id) => *subject_id, + Key::Draft(handle) => *allocated_subjects + .get(handle) + .expect("a draft subject reference resolved above"), + } + }; + let edge_id_of = |key: &Key| -> EdgeId { + match key { + Key::Existing(edge_id) => *edge_id, + Key::Draft(handle) => *allocated_routes + .get(handle) + .expect("a draft route reference resolved above"), + } + }; + let target_of = |target: &DependencyRef| -> DependencyTarget { + match target { + DependencyRef::Resource(reference) => { + DependencyTarget::Resource(entity_id_of(&key_of(reference))) + } + DependencyRef::Route(reference) => { + DependencyTarget::Route(edge_id_of(&key_of(reference))) + } + DependencyRef::Subject(reference) => { + DependencyTarget::Subject(subject_id_of(&key_of(reference))) + } + } + }; + let authority_target_of = |target: &AuthorityTargetRef| -> AuthorityTarget { + match target { + AuthorityTargetRef::Subject(reference) => { + AuthorityTarget::Subject(subject_id_of(&key_of(reference))) + } + AuthorityTargetRef::PlaceSubtree(reference) => { + AuthorityTarget::PlaceSubtree(entity_id_of(&key_of(reference))) + } + } + }; + let reach_of = |reach: &ReachRef| -> Reach { + match reach { + ReachRef::Subjects(members) => Reach::Subjects( + members + .iter() + .map(|reference| subject_id_of(&key_of(reference))) + .collect(), + ), + ReachRef::Place(reference) => Reach::Place(entity_id_of(&key_of(reference))), + } + }; + let controller_of = |controller: &Option>| -> Option { + controller + .as_ref() + .map(|reference| subject_id_of(&key_of(reference))) + }; + let audience_of = |audience: &AudienceRef| -> Audience { + match audience { + AudienceRef::Colocated => Audience::Colocated, + AudienceRef::Channel(reference) => Audience::Channel(entity_id_of(&key_of(reference))), + } + }; + let mut declared_facts = Vec::new(); + let mut declared_channels = Vec::new(); + for declaration in &patch.declarations { + match declaration { + Declaration::Fact(fact) => declared_facts.push(ResolvedFact { + handle: fact.handle.clone(), + entity_id: entity_id_of(&Key::Draft(fact.handle.clone())), + entity: EntityRecord { + label: fact.label.clone(), + kind: EntityKind::Fact, + container: None, + }, + fact: FactRecord { + statement: fact.statement.clone(), + standing: match &fact.standing { + FactStandingRef::Canonical { evidence } => FactStanding::Canonical { + evidence: evidence.clone(), + }, + FactStandingRef::Claimed { by } => FactStanding::Claimed { + by: subject_id_of(&key_of(by)), + }, + FactStandingRef::Ruled => FactStanding::Ruled, + }, + }, + }), + Declaration::Channel(channel) => declared_channels.push(ResolvedChannel { + handle: channel.handle.clone(), + entity_id: entity_id_of(&Key::Draft(channel.handle.clone())), + entity: EntityRecord { + label: channel.label.clone(), + kind: EntityKind::Channel, + container: None, + }, + channel: ChannelRecord { + reach: reach_of(&channel.reach), + controller: controller_of(&channel.controller), + }, + }), + _ => {} + } + } + let grant_of = |grant: &AuthorityGrantRef| -> AuthorityGrant { + AuthorityGrant { + kind: grant.kind.clone(), + over: authority_target_of(&grant.over), + } + }; + let precondition_of = |check: &PreconditionRef| -> BoundPrecondition { + match check { + PreconditionRef::Present { at } => BoundPrecondition::Present { + at: entity_id_of(&key_of(at)), + }, + PreconditionRef::Reachable { to, within } => BoundPrecondition::Reachable { + to: entity_id_of(&key_of(to)), + within: *within, + }, + PreconditionRef::Holds { resource, at_least } => BoundPrecondition::Holds { + resource: entity_id_of(&key_of(resource)), + at_least: *at_least, + }, + PreconditionRef::Authorized { over, kind } => BoundPrecondition::Authorized { + over: authority_target_of(over).as_referent(), + kind: kind.clone(), + }, + PreconditionRef::HasStanding { grievance } => BoundPrecondition::HasStanding { + grievance: grievance.clone(), + }, + PreconditionRef::Knows { fact, at_least } => BoundPrecondition::Knows { + fact: entity_id_of(&key_of(fact)), + at_least: *at_least, + }, + PreconditionRef::CanBroadcast { via } => BoundPrecondition::CanBroadcast { + via: audience_of(via), + }, + PreconditionRef::CanReach { subject, via } => BoundPrecondition::CanReach { + subject: subject_id_of(&key_of(subject)), + via: audience_of(via), + }, + PreconditionRef::Committed { to, kind } => BoundPrecondition::Committed { + to: subject_id_of(&key_of(to)), + kind: *kind, + }, + } + }; + let pressure_source_of = |source: &PressureSourceRef| -> PressureSource { + match source { + PressureSourceRef::Commitment { subject, key } => PressureSource::Commitment { + subject: subject_id_of(&key_of(subject)), + key: *key, + }, + PressureSourceRef::Dependency(target) => PressureSource::Dependency(target_of(target)), + PressureSourceRef::Subject(reference) => { + PressureSource::Subject(subject_id_of(&key_of(reference))) + } + } + }; + let operations = patch + .operations + .iter() + .enumerate() + .map(|(position, operation)| match operation { + ComponentOp::CreateCommitment { + subject, + counterparty, + kind, + due, + period, + checks, + statement, + } => ResolvedOp::CreateCommitment { + subject: subject_id_of(&key_of(subject)), + key: CommitmentKey { + command: command_id, + index: position as u32, + }, + commitment: Commitment { + kind: *kind, + counterparty: counterparty + .as_ref() + .map(|reference| subject_id_of(&key_of(reference))), + due: *due, + period: *period, + checks: checks.iter().map(precondition_of).collect(), + statement: statement.clone(), + }, + }, + ComponentOp::DischargeCommitment { subject, key } => ResolvedOp::DischargeCommitment { + subject: subject_id_of(&key_of(subject)), + key: *key, + }, + ComponentOp::AdvancePressure { source, target, by } => ResolvedOp::AdvancePressure { + source: pressure_source_of(source), + target: subject_id_of(&key_of(target)), + by: *by, + }, + ComponentOp::ReducePressure { source, target, by } => ResolvedOp::ReducePressure { + source: pressure_source_of(source), + target: subject_id_of(&key_of(target)), + by: *by, + }, + ComponentOp::ResolvePressure { source, target } => ResolvedOp::ResolvePressure { + source: pressure_source_of(source), + target: subject_id_of(&key_of(target)), + }, + ComponentOp::Retire { subject } => ResolvedOp::Retire { + subject: subject_id_of(&key_of(subject)), + }, + ComponentOp::GrantAffordance { + subject, + affordance, + } => ResolvedOp::GrantAffordance { + subject: subject_id_of(&key_of(subject)), + affordance: affordance_id_of(&key_of(affordance)), + }, + ComponentOp::RevokeAffordance { + subject, + affordance, + } => ResolvedOp::RevokeAffordance { + subject: subject_id_of(&key_of(subject)), + affordance: affordance_id_of(&key_of(affordance)), + }, + ComponentOp::Relocate { subject, via } => ResolvedOp::Relocate { + subject_id: subject_id_of(&key_of(subject)), + edge_id: edge_id_of(&key_of(via)), + }, + ComponentOp::OpenRoute { route } => ResolvedOp::OpenRoute { + edge_id: edge_id_of(&key_of(route)), + }, + ComponentOp::CloseRoute { route } => ResolvedOp::CloseRoute { + edge_id: edge_id_of(&key_of(route)), + }, + ComponentOp::AlterCost { route, cost } => ResolvedOp::AlterCost { + edge_id: edge_id_of(&key_of(route)), + cost: *cost, + }, + ComponentOp::Transfer { + from, + to, + resource, + qty, + } => ResolvedOp::Transfer { + from: subject_id_of(&key_of(from)), + to: subject_id_of(&key_of(to)), + resource: entity_id_of(&key_of(resource)), + qty: *qty, + }, + ComponentOp::Transform { + holder, + from_resource, + into_resource, + qty, + } => ResolvedOp::Transform { + holder: subject_id_of(&key_of(holder)), + from_resource: entity_id_of(&key_of(from_resource)), + into_resource: entity_id_of(&key_of(into_resource)), + qty: *qty, + }, + ComponentOp::Consume { + holder, + resource, + qty, + } => ResolvedOp::Consume { + holder: subject_id_of(&key_of(holder)), + resource: entity_id_of(&key_of(resource)), + qty: *qty, + }, + ComponentOp::Admit { + holder, + resource, + qty, + evidence, + } => ResolvedOp::Admit { + holder: subject_id_of(&key_of(holder)), + resource: entity_id_of(&key_of(resource)), + qty: *qty, + evidence: evidence.clone(), + }, + ComponentOp::Mint { + holder, + resource, + qty, + } => ResolvedOp::Mint { + holder: subject_id_of(&key_of(holder)), + resource: entity_id_of(&key_of(resource)), + qty: *qty, + }, + ComponentOp::Bind { subject, target } => ResolvedOp::Bind { + subject: subject_id_of(&key_of(subject)), + target: target_of(target), + }, + ComponentOp::Release { subject, target } => ResolvedOp::Release { + subject: subject_id_of(&key_of(subject)), + target: target_of(target), + }, + ComponentOp::GrantAuthority { holder, grant } => ResolvedOp::GrantAuthority { + holder: subject_id_of(&key_of(holder)), + grant: grant_of(grant), + }, + ComponentOp::RevokeAuthority { holder, grant } => ResolvedOp::RevokeAuthority { + holder: subject_id_of(&key_of(holder)), + grant: grant_of(grant), + }, + ComponentOp::OpenOffice { + institution, + office, + delegated, + } => ResolvedOp::OpenOffice { + institution: subject_id_of(&key_of(institution)), + office: office.clone(), + delegated: delegated.clone(), + }, + ComponentOp::CloseOffice { + institution, + office, + } => ResolvedOp::CloseOffice { + institution: subject_id_of(&key_of(institution)), + office: office.clone(), + }, + ComponentOp::InstallIncumbent { + institution, + office, + incumbent, + } => ResolvedOp::InstallIncumbent { + institution: subject_id_of(&key_of(institution)), + office: office.clone(), + incumbent: subject_id_of(&key_of(incumbent)), + }, + ComponentOp::VacateOffice { + institution, + office, + } => ResolvedOp::VacateOffice { + institution: subject_id_of(&key_of(institution)), + office: office.clone(), + }, + ComponentOp::OpenForum { + grievance, + forum, + standing, + } => ResolvedOp::OpenForum { + grievance: grievance.clone(), + forum: subject_id_of(&key_of(forum)), + standing: authority_target_of(standing), + }, + ComponentOp::CloseForum { grievance } => ResolvedOp::CloseForum { + grievance: grievance.clone(), + }, + ComponentOp::AcquireKnowledge { + subject, + fact, + source, + confidence, + } => ResolvedOp::AcquireKnowledge { + subject: subject_id_of(&key_of(subject)), + fact: entity_id_of(&key_of(fact)), + source: *source, + confidence: *confidence, + }, + ComponentOp::Communicate { speaker, fact, to } => ResolvedOp::Communicate { + speaker: subject_id_of(&key_of(speaker)), + fact: entity_id_of(&key_of(fact)), + to: audience_of(to), + }, + ComponentOp::Witness { + fact, + place, + confidence, + } => ResolvedOp::Witness { + fact: entity_id_of(&key_of(fact)), + place: entity_id_of(&key_of(place)), + confidence: *confidence, + }, + ComponentOp::Forget { subject, fact } => ResolvedOp::Forget { + subject: subject_id_of(&key_of(subject)), + fact: entity_id_of(&key_of(fact)), + }, + ComponentOp::SetReach { channel, reach } => ResolvedOp::SetReach { + channel: entity_id_of(&key_of(channel)), + reach: reach_of(reach), + }, + ComponentOp::SetPersonaMaterial { + subject, + values, + voice, + memories, + reads, + } => ResolvedOp::SetPersonaMaterial { + subject: subject_id_of(&key_of(subject)), + material: PersonaMaterial { + values: values.clone(), + voice: voice.clone(), + memories: memories.clone(), + reads: reads + .iter() + .map(|read| (subject_id_of(&key_of(&read.subject)), read.statement.clone())) + .collect(), + }, + }, + ComponentOp::SetController { + channel, + controller, + } => ResolvedOp::SetController { + channel: entity_id_of(&key_of(channel)), + controller: controller_of(controller), + }, + }) + .collect(); + + if !collisions.is_empty() { + collisions.sort(); + return Err(collisions); + } + + Ok(ResolvedPatch { + subjects, + entities, + routes, + affordances, + facts: declared_facts, + channels: declared_channels, + operations, + evidence: patch.evidence.clone(), + scale_intent: scale_intent.map(|intent| WorldScaleIntent { + targets: intent.targets.clone(), + jurisdictions: intent + .jurisdictions + .iter() + .map(|(handle, weight)| { + ( + *allocated_entities + .get(handle) + .expect("a jurisdiction root resolved above"), + *weight, + ) + }) + .collect(), + }), + lens_weights: lens_weights.cloned(), + }) +} + +/// Whether every referent one stored check names resolves. The canonical +/// lowering runs after allocation, so a check that does not resolve here would +/// have nothing to lower to. +fn resolve_check( + site: Site, + check: &PreconditionRef, + index: &BTreeMap, + state: &super::WorldState, + mismatches: &mut Vec, +) -> bool { + let entity = |kind: EntityKind, reference: &Ref, mismatches: &mut Vec| { + resolve_entity( + site.clone(), + kind, + reference, + index, + &state.entities, + mismatches, + ) + .is_some() + }; + let audience = |via: &AudienceRef, mismatches: &mut Vec| { + resolve_audience(site.clone(), via, index, state, mismatches).is_some() + }; + let subject = |reference: &Ref, mismatches: &mut Vec| { + resolve_subject(site.clone(), reference, index, &state.subjects, mismatches).is_some() + }; + match check { + PreconditionRef::Present { at } => entity(EntityKind::Place, at, mismatches), + PreconditionRef::Reachable { to, within } => { + let resolved = entity(EntityKind::Place, to, mismatches); + if !is_valid_cost(*within) { + mismatches.push(Mismatch::InvalidCost { site: site.clone() }); + return false; + } + resolved + } + PreconditionRef::Holds { resource, .. } => { + entity(EntityKind::Resource, resource, mismatches) + } + PreconditionRef::Authorized { over, kind } => { + let resolved = + resolve_authority_target(site.clone(), over, index, state, mismatches).is_some(); + if !is_civic_name(&kind.0) { + mismatches.push(Mismatch::InvalidCivicName { site: site.clone() }); + return false; + } + resolved + } + PreconditionRef::HasStanding { grievance } => { + if is_civic_name(&grievance.0) { + true + } else { + mismatches.push(Mismatch::InvalidCivicName { site: site.clone() }); + false + } + } + PreconditionRef::Knows { fact, .. } => entity(EntityKind::Fact, fact, mismatches), + PreconditionRef::CanBroadcast { via } => audience(via, mismatches), + PreconditionRef::CanReach { + subject: named, + via, + } => subject(named, mismatches) & audience(via, mismatches), + PreconditionRef::Committed { to, .. } => subject(to, mismatches), + } +} + +fn resolve_pressure_source( + site: Site, + source: &PressureSourceRef, + index: &BTreeMap, + state: &super::WorldState, + mismatches: &mut Vec, +) -> Option { + match source { + PressureSourceRef::Commitment { subject, key } => { + resolve_subject(site, subject, index, &state.subjects, mismatches) + .map(|subject| PressureSourceKey::Commitment { subject, key: *key }) + } + PressureSourceRef::Dependency(target) => { + resolve_dependency_target(site, target, index, state, mismatches) + .map(PressureSourceKey::Dependency) + } + PressureSourceRef::Subject(reference) => { + resolve_subject(site, reference, index, &state.subjects, mismatches) + .map(PressureSourceKey::Subject) + } + } +} + +/// Whether `place` is `root`, or reaches it through the candidate container +/// chain. The walk is bounded by the graph size, so a cycle that does not +/// include either end still terminates. +fn key_covers_place( + root: &Key, + place: &Key, + containers: &BTreeMap, Key>, +) -> bool { + let mut current = Some(place); + for _ in 0..=containers.len() { + match current { + None => return false, + Some(node) if node == root => return true, + Some(node) => current = containers.get(node), + } + } + false +} + +/// Whether a place reaches itself through its container chain: the same walk, +/// started one link up so a place is not its own ancestor by definition. +fn contains_itself( + start: &Key, + containers: &BTreeMap, Key>, +) -> bool { + containers + .get(start) + .is_some_and(|parent| key_covers_place(start, parent, containers)) +} + +/// Whether `place` is `root` or is contained in it, over canonical state: one +/// upward walk in the shape of [`containment_terminates`], bounded by the graph +/// size. It is total because `admit_resolved` refuses a non-terminating chain, +/// so the bound is belt-and-braces rather than a repair loop. There is no +/// downward enumeration and no child index: every jurisdictional question this +/// kernel asks is "is this target inside my ground". +pub(super) fn covers_place( + entities: &BTreeMap, + root: EntityId, + place: EntityId, +) -> bool { + let mut current = Some(place); + for _ in 0..=entities.len() { + match current { + None => return false, + Some(node) if node == root => return true, + Some(node) => current = entities.get(&node).and_then(|record| record.container), + } + } + false +} + +/// The canonical twin of the candidate graph's `candidate_targets_overlap`: whether two +/// jurisdictions of one kind cover common ground. +pub(super) fn targets_overlap( + entities: &BTreeMap, + left: AuthorityTarget, + right: AuthorityTarget, +) -> bool { + match (left, right) { + (AuthorityTarget::Subject(one), AuthorityTarget::Subject(other)) => one == other, + (AuthorityTarget::PlaceSubtree(one), AuthorityTarget::PlaceSubtree(other)) => { + covers_place(entities, one, other) || covers_place(entities, other, one) + } + _ => false, + } +} + +/// Whether a subject holding `grants` may traverse a route with this access +/// rule toward `destination`. The sole statement of the `Restricted` rule, +/// called by `resolve_patch`'s `Relocate` arm, by `apply_operation`'s, and by +/// `Precondition::Reachable`'s edge admission — one rule, three callers, no +/// drift. Openness is a separate claim with its own name, so it is not folded +/// in here. +pub(super) fn route_admits( + state: &super::WorldState, + grants: &BTreeSet, + access: &AccessKind, + destination: EntityId, +) -> bool { + match access { + AccessKind::Public => true, + AccessKind::Restricted { requires } => grants.iter().any(|grant| { + &grant.kind == requires + && super::covers(state, grant.over, super::Target::Entity(destination)) + }), + } +} + +/// The same containment walk over canonical state, for the admission and replay +/// invariants. `admit_resolved` runs it after inserting a place, so a container +/// chain that never terminates dies before the partition keeps it. +pub(super) fn containment_terminates( + start: EntityId, + entities: &BTreeMap, +) -> bool { + let mut current = entities.get(&start).and_then(|record| record.container); + for _ in 0..=entities.len() { + match current { + None => return true, + Some(node) if node == start => return false, + Some(node) => current = entities.get(&node).and_then(|record| record.container), + } + } + false +} +#[cfg(test)] +mod tests { + use super::*; + use crate::tests::{ + ADMIT_KIND, FIXTURE_ENTITIES, LEVY_KIND, activate, admit_topology, authority_kind, + auth_principal, civic_world, command, creation, grant_to, human_principal, office, + over_place, owner, reject_owner, speak_entry, submit_owner, + }; + use crate::{ + CallerId, CommandBody, CommandId, KernelError, SubmitReceipt, WorldKernel, WorldPhase, + }; + + /// Owner: `WorldPatch::sets_persona_of_existing_subject`. Consumer: + /// `ghostlight-dungeon`'s play agent (PA.f61, parked at + /// `parked/ghostlight-eve-surface`), which refuses a + /// `set_persona_material` run whose patch answers true here, since + /// `WorldPatch`'s own fields are `pub(crate)` and Dungeon may not parse + /// its JSON to decide the question itself. + #[test] + fn sets_persona_of_existing_subject_reads_the_subject_refs_own_shape() { + let empty = WorldPatch::default(); + assert!(!empty.sets_persona_of_existing_subject()); + + let existing = WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::SetPersonaMaterial { + subject: Ref::Existing(SubjectId::issue()), + values: Vec::new(), + voice: Statement::new("flat and even").unwrap(), + memories: Vec::new(), + reads: Vec::new(), + }], + evidence: Vec::new(), + }; + assert!(existing.sets_persona_of_existing_subject()); + + let draft = WorldPatch { + declarations: Vec::new(), + operations: vec![ComponentOp::SetPersonaMaterial { + subject: Ref::Draft(DraftHandle::new("npc")), + values: Vec::new(), + voice: Statement::new("flat and even").unwrap(), + memories: Vec::new(), + reads: Vec::new(), + }], + evidence: Vec::new(), + }; + assert!(!draft.sets_persona_of_existing_subject()); + } + + /// PA.f92/PA.f110: a fixture whose persona write sits at either end of + /// `operations` only ever exercises `.take(1)` (op 0) or `.rev().take(1)` + /// (the last op) — the prior version of this test put the write last, + /// so `.rev().take(1)` would still find it and pass undetected. Here the + /// persona write to an existing subject sits strictly in the *middle*, + /// with a harmless `Relocate` both before and after it: only a scan over + /// every operation, in either direction, reports `true`. + #[test] + fn sets_persona_of_existing_subject_scans_every_operation_not_just_an_end() { + let patch = WorldPatch { + declarations: Vec::new(), + operations: vec![ + ComponentOp::Relocate { + subject: Ref::Draft(DraftHandle::new("wanderer")), + via: Ref::Draft(DraftHandle::new("path")), + }, + ComponentOp::SetPersonaMaterial { + subject: Ref::Existing(SubjectId::issue()), + values: Vec::new(), + voice: Statement::new("flat and even").unwrap(), + memories: Vec::new(), + reads: Vec::new(), + }, + ComponentOp::Relocate { + subject: Ref::Draft(DraftHandle::new("wanderer")), + via: Ref::Draft(DraftHandle::new("second-path")), + }, + ], + evidence: Vec::new(), + }; + // Op 0 and the last op (index 2) are both the harmless `Relocate`; + // only op 1, strictly in the middle, is the persona write. A + // `.take(1)` mutation sees only op 0; a `.rev().take(1)` mutation + // sees only op 2. Both would report `false` here. + assert!(patch.sets_persona_of_existing_subject()); + } + + fn entity(handle: &str, label: &str, kind: EntityKind) -> Declaration { + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind, + container: None, + }) + } + + fn contained(handle: &str, label: &str, container: &str) -> Declaration { + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: EntityKind::Place, + container: Some(Ref::Draft(DraftHandle::new(container))), + }) + } + + fn route(handle: &str, label: &str, from: &str, to: &str, cost: u32) -> Declaration { + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + from: Ref::Draft(DraftHandle::new(from)), + to: Ref::Draft(DraftHandle::new(to)), + access: AccessKind::Public, + cost: Cost(cost), + }) + } + + /// Every fixture institution is declared by a post-genesis `AdmitPatch`, so + /// it grants the committed Speak entry by canonical reference: the kernel + /// synthesizes that entry once, at genesis, and a later patch names it like + /// any other structure a previous commit allocated. + fn institution( + kernel: &WorldKernel, + handle: &str, + label: &str, + position: Option>, + ) -> Declaration { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: SubjectKind::Institution, + controller: NewController::OperationalAgent, + affordances: BTreeSet::from([speak_entry(kernel)]), + position, + import_key: None, + }) + } + + fn patch_of(declarations: Vec) -> WorldPatch { + WorldPatch { + declarations, + operations: Vec::new(), + evidence: Vec::new(), + } + } + + fn operations_of(operations: Vec) -> WorldPatch { + WorldPatch { + declarations: Vec::new(), + operations, + evidence: Vec::new(), + } + } + + fn draft(handle: &str) -> DraftHandle { + DraftHandle::new(handle) + } + + fn at(handle: &str) -> Site { + Site::Declaration(DraftHandle::new(handle)) + } + + fn admit(patch: WorldPatch) -> CommandBody { + CommandBody::AdmitPatch { + answers: None, + patch, + } + } + + /// A minimal admissible entry, so a validation test changes exactly one + /// thing and names exactly one rejection. + fn catalog_entry( + handle: &str, + kind: &str, + roles: Vec, + effect_slots: Vec, + outcome_bands: Vec, + ) -> Declaration { + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new(handle), + kind: AffordanceKindName(kind.into()), + roles, + preconditions: Vec::new(), + effect_slots, + outcome_bands, + carries_speech: false, + }) + } + + fn role_spec(role: &str, kind: RefKind) -> RoleSpec { + RoleSpec { + role: Role(role.into()), + kind, + } + } + + fn transfer_slot(roles: Vec<&str>, bounds: Bounds) -> EffectSlot { + EffectSlot { + op_kind: ComponentOpKind::Transfer, + roles: roles.into_iter().map(|role| Role(role.into())).collect(), + bounds, + } + } + + fn transfer_roles() -> Vec { + vec![ + role_spec("from", RefKind::Subject(None)), + role_spec("to", RefKind::Subject(None)), + role_spec("goods", RefKind::Entity(EntityKind::Resource)), + ] + } + + fn band(effects: Vec) -> OutcomeBand { + OutcomeBand { weight: 1, effects } + } + + #[test] + fn a_catalog_entry_with_a_dangling_or_noncanonical_band_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let before = kernel.snapshot().unwrap(); + let slots = vec![ + transfer_slot(vec!["from", "to", "goods"], Bounds::Quantity(Quantity(2))), + transfer_slot(vec!["from", "to", "goods"], Bounds::Quantity(Quantity(2))), + ]; + let handle = DraftHandle::new("verb"); + + for (bands, expected) in [ + ( + vec![band(vec![2])], + Mismatch::DanglingBandEffect { + handle: handle.clone(), + band: 0, + }, + ), + ( + vec![band(vec![1, 0])], + Mismatch::BandEffectsNotCanonical { + handle: handle.clone(), + band: 0, + }, + ), + ( + vec![OutcomeBand { + weight: 0, + effects: vec![0], + }], + Mismatch::ZeroBandWeight { + handle: handle.clone(), + band: 0, + }, + ), + ( + Vec::new(), + Mismatch::NoOutcomeBand { + handle: handle.clone(), + }, + ), + ] { + let rejected = reject_owner( + &mut kernel, + &before, + admit(patch_of(vec![catalog_entry( + "verb", + "verb", + transfer_roles(), + slots.clone(), + bands, + )])), + ); + assert_eq!(rejected, vec![expected]); + assert!(kernel.state.affordance_catalog.len() == before.affordances.len()); + } + + // No effect slots and no speech: the entry could never change anything. + let rejected = reject_owner( + &mut kernel, + &before, + admit(patch_of(vec![catalog_entry( + "verb", + "verb", + Vec::new(), + Vec::new(), + vec![band(Vec::new())], + )])), + ); + assert_eq!(rejected, vec![Mismatch::InertAffordance { handle }]); + } + + #[test] + fn a_slot_whose_roles_do_not_match_its_operation_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let before = kernel.snapshot().unwrap(); + let handle = DraftHandle::new("verb"); + + // A `Transfer` takes three referents, not two. + assert_eq!( + reject_owner( + &mut kernel, + &before, + admit(patch_of(vec![catalog_entry( + "verb", + "verb", + transfer_roles(), + vec![transfer_slot( + vec!["from", "to"], + Bounds::Quantity(Quantity(2)) + )], + vec![band(vec![0])], + )])), + ), + vec![Mismatch::SlotRoleArity { + handle: handle.clone(), + slot: 0 + }] + ); + + // Its third referent is a resource, not a place. + assert_eq!( + reject_owner( + &mut kernel, + &before, + admit(patch_of(vec![catalog_entry( + "verb", + "verb", + vec![ + role_spec("from", RefKind::Subject(None)), + role_spec("to", RefKind::Subject(None)), + role_spec("goods", RefKind::Entity(EntityKind::Place)), + ], + vec![transfer_slot( + vec!["from", "to", "goods"], + Bounds::Quantity(Quantity(2)) + )], + vec![band(vec![0])], + )])), + ), + vec![Mismatch::RoleKindUnfit { + handle: handle.clone(), + role: Role("goods".into()) + }] + ); + + // A `Transfer` carries a quantity, so an unbounded slot has no ceiling. + assert_eq!( + reject_owner( + &mut kernel, + &before, + admit(patch_of(vec![catalog_entry( + "verb", + "verb", + transfer_roles(), + vec![transfer_slot(vec!["from", "to", "goods"], Bounds::None)], + vec![band(vec![0])], + )])), + ), + vec![Mismatch::SlotBoundMismatch { + handle: handle.clone(), + slot: 0 + }] + ); + + // A slot naming a role the entry does not declare. + assert_eq!( + reject_owner( + &mut kernel, + &before, + admit(patch_of(vec![catalog_entry( + "verb", + "verb", + transfer_roles(), + vec![transfer_slot( + vec!["from", "to", "cargo"], + Bounds::Quantity(Quantity(2)) + )], + vec![band(vec![0])], + )])), + ), + vec![Mismatch::UnknownRole { + handle, + role: Role("cargo".into()) + }] + ); + } + + #[test] + fn a_grant_naming_an_undeclared_affordance_is_rejected_and_the_same_patch_commits() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let before = kernel.snapshot().unwrap(); + let entries_before = kernel.state.affordance_catalog.len(); + let subjects_before = kernel.state.subjects.len(); + + let granting = |handle: &str| { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("late-arrival"), + label: "A Late Arrival".into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + affordances: BTreeSet::from([Ref::Draft(DraftHandle::new(handle))]), + position: None, + import_key: None, + }) + }; + + assert_eq!( + reject_owner( + &mut kernel, + &before, + admit(patch_of(vec![granting("verb")])) + ), + vec![Mismatch::UnresolvedDraft { + site: Site::Declaration(DraftHandle::new("late-arrival")), + referent: DraftHandle::new("verb"), + expected: RefKind::Affordance, + }] + ); + assert_eq!(kernel.state.affordance_catalog.len(), entries_before); + assert_eq!(kernel.state.subjects.len(), subjects_before); + + // Declaring the entry in the same patch commits both atomically. + let receipt = submit_owner( + &mut kernel, + &before, + admit(patch_of(vec![ + catalog_entry( + "verb", + "verb", + transfer_roles(), + vec![transfer_slot( + vec!["from", "to", "goods"], + Bounds::Quantity(Quantity(2)), + )], + vec![band(vec![0])], + ), + granting("verb"), + ])), + ); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert_eq!(kernel.state.affordance_catalog.len(), entries_before + 1); + assert_eq!(kernel.state.subjects.len(), subjects_before + 1); + let granted = kernel + .state + .affordance_grants + .values() + .find(|entries| entries.len() == 1) + .expect("the new subject's grant set"); + assert!( + granted + .iter() + .all(|id| kernel.state.affordance_catalog.contains_key(id)) + ); + } + + #[test] + fn two_entries_cannot_share_one_kind_name() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let before = kernel.snapshot().unwrap(); + let slot = transfer_slot(vec!["from", "to", "goods"], Bounds::Quantity(Quantity(2))); + let rejected = reject_owner( + &mut kernel, + &before, + admit(patch_of(vec![ + catalog_entry( + "first", + "haul", + transfer_roles(), + vec![slot.clone()], + vec![band(vec![0])], + ), + catalog_entry( + "second", + "haul", + transfer_roles(), + vec![slot], + vec![band(vec![0])], + ), + ])), + ); + assert_eq!( + rejected, + vec![Mismatch::DuplicateAffordanceKind { + handle: DraftHandle::new("second") + }] + ); + + // A kind name outside the tool-name alphabet is refused for the same + // reason: it becomes a generated tool name. + let rejected = reject_owner( + &mut kernel, + &before, + admit(patch_of(vec![catalog_entry( + "loud", + "Haul It", + transfer_roles(), + vec![transfer_slot( + vec!["from", "to", "goods"], + Bounds::Quantity(Quantity(2)), + )], + vec![band(vec![0])], + )])), + ); + assert_eq!( + rejected, + vec![Mismatch::InvalidAffordanceName { + handle: DraftHandle::new("loud") + }] + ); + } + + fn draft_world(directory: &std::path::Path) -> WorldKernel { + WorldKernel::create( + directory.join("world.cc"), + creation(CommandId::new(), "Kharad"), + &auth_principal(owner()), + ) + .expect("draft world") + .0 + } + + /// The position reference names a place that no declaration and no partition + /// provides. Nothing commits and nothing is allocated. + #[test] + fn a_subject_declared_at_an_undeclared_place_is_rejected_and_allocates_nothing() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let before = kernel.snapshot().unwrap(); + let commits_before = kernel.journal.commit_count(); + + let error = kernel + .submit( + command( + &before, + CommandId::new(), + CallerId::Principal(owner()), + admit(patch_of(vec![institution( + &kernel, + "rhythm-authority", + "The Rhythm Authority", + Some(Ref::Draft(DraftHandle::new("kharad-rhythm-road"))), + )])), + ), + &auth_principal(owner()), + ) + .unwrap_err(); + + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + assert_eq!( + mismatches, + vec![Mismatch::UnresolvedDraft { + site: at("rhythm-authority"), + referent: draft("kharad-rhythm-road"), + expected: PLACE, + }] + ); + assert_eq!(kernel.snapshot().unwrap(), before); + assert_eq!(kernel.journal.commit_count(), commits_before); + assert_eq!(kernel.state.entities.len(), FIXTURE_ENTITIES); + assert_eq!(kernel.state.subjects.len(), before.subjects.len()); + } + + /// A place, a route into it, and a subject standing there are one atomic + /// commit: every reference resolves to an ID the same patch allocated. + #[test] + fn a_declared_place_and_its_dependents_commit_atomically() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let before = kernel.snapshot().unwrap(); + let commits_before = kernel.journal.commit_count(); + + let patch = patch_of(vec![ + entity("cavity-yard", "The Cavity Yard", EntityKind::Place), + entity("kharad-rhythm-road", "The Rhythm Road", EntityKind::Place), + route( + "yard-road", + "The Yard Ramp", + "cavity-yard", + "kharad-rhythm-road", + 12, + ), + institution( + &kernel, + "rhythm-authority", + "The Rhythm Authority", + Some(Ref::Draft(draft("kharad-rhythm-road"))), + ), + ]); + let receipt = submit_owner(&mut kernel, &before, admit(patch)); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + + let after = kernel.snapshot().unwrap(); + assert_eq!(after.revision, before.revision + 1); + assert_eq!(kernel.journal.commit_count(), commits_before + 1); + assert_eq!(kernel.state.entities.len(), 3); + let road = *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == "The Rhythm Road") + .expect("the road is admitted") + .0; + let yard = *kernel + .state + .entities + .iter() + .find(|(_, record)| record.label == "The Cavity Yard") + .expect("the yard is admitted") + .0; + let (_, edge) = kernel.state.edges.iter().next().expect("the route lands"); + assert_eq!(edge.endpoints(), (yard, road)); + assert_eq!(edge.cost(), Cost(12)); + assert!(edge.is_open()); + let admitted = *kernel + .state + .subjects + .iter() + .find(|(_, subject)| subject.label == "The Rhythm Authority") + .expect("the institution is admitted") + .0; + assert_eq!( + kernel.state.positions.get(&admitted), + Some(&Position { place: road }) + ); + } + + /// A handle of the wrong namespace kind is a runtime mismatch. The + /// cross-namespace canonical case is a compile error instead: + /// `Ref::::Existing(subject_id)` does not compile, because + /// `SubjectId`, `EntityId`, and `EdgeId` are distinct newtypes with no + /// conversion between them and no public `Uuid` constructor. + #[test] + fn a_draft_handle_of_the_wrong_kind_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let before = kernel.snapshot().unwrap(); + let commits_before = kernel.journal.commit_count(); + + let error = kernel + .submit( + command( + &before, + CommandId::new(), + CallerId::Principal(owner()), + admit(patch_of(vec![ + entity("rhythm-tithe", "The Rhythm Tithe", EntityKind::Resource), + institution( + &kernel, + "rhythm-authority", + "The Rhythm Authority", + Some(Ref::Draft(DraftHandle::new("rhythm-tithe"))), + ), + ])), + ), + &auth_principal(owner()), + ) + .unwrap_err(); + + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + assert_eq!( + mismatches, + vec![Mismatch::WrongKind { + site: at("rhythm-authority"), + referent: RefName::Entity(Ref::Draft(draft("rhythm-tithe"))), + expected: PLACE, + actual: RefKind::Entity(EntityKind::Resource), + }] + ); + assert_eq!(kernel.journal.commit_count(), commits_before); + assert_eq!(kernel.snapshot().unwrap(), before); + } + + /// Rejection carries the complete failed-check set, not the first failure, + /// and repairing exactly that set is enough to commit. + #[test] + fn rejection_returns_every_failed_check_and_repairing_exactly_those_commits() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let before = kernel.snapshot().unwrap(); + + let broken = patch_of(vec![ + entity("rhythm-road", "The Rhythm Road", EntityKind::Place), + entity("rhythm-road", " ", EntityKind::Place), + institution( + &kernel, + "rhythm-authority", + "The Rhythm Authority", + Some(Ref::Draft(DraftHandle::new("cavity-yard"))), + ), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("late-arrival"), + label: "A Late Arrival".into(), + kind: SubjectKind::Person, + controller: NewController::Human { + principal: human_principal(), + }, + affordances: BTreeSet::from([speak_entry(&kernel)]), + position: None, + import_key: None, + }), + ]); + let error = kernel + .submit( + command( + &before, + CommandId::new(), + CallerId::Principal(owner()), + admit(broken), + ), + &auth_principal(owner()), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + let mut expected = vec![ + Mismatch::DuplicateHandle { + handle: DraftHandle::new("rhythm-road"), + }, + Mismatch::EmptyLabel { + handle: DraftHandle::new("rhythm-road"), + }, + Mismatch::UnresolvedDraft { + site: at("rhythm-authority"), + referent: draft("cavity-yard"), + expected: PLACE, + }, + Mismatch::UnadmittedController { + handle: DraftHandle::new("late-arrival"), + }, + ]; + expected.sort(); + assert_eq!(mismatches, expected); + assert_eq!(kernel.journal.commit_count(), 1); + + let repaired = patch_of(vec![ + entity("rhythm-road", "The Rhythm Road", EntityKind::Place), + entity("cavity-yard", "The Cavity Yard", EntityKind::Place), + institution( + &kernel, + "rhythm-authority", + "The Rhythm Authority", + Some(Ref::Draft(DraftHandle::new("cavity-yard"))), + ), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("late-arrival"), + label: "A Late Arrival".into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + affordances: BTreeSet::from([speak_entry(&kernel)]), + position: None, + import_key: None, + }), + ]); + let receipt = submit_owner(&mut kernel, &before, admit(repaired)); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert_eq!(kernel.state.entities.len(), 3); + } + + #[test] + fn an_empty_patch_is_no_canonical_change() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let before = kernel.snapshot().unwrap(); + + let error = kernel + .submit( + command( + &before, + CommandId::new(), + CallerId::Principal(owner()), + admit(patch_of(Vec::new())), + ), + &auth_principal(owner()), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + assert_eq!(mismatches, vec![Mismatch::NoCanonicalChange]); + assert_eq!(kernel.snapshot().unwrap(), before); + assert_eq!(kernel.journal.commit_count(), 1); + } + + /// Active admits the four operations and nothing else, so it never mints a + /// canonical ID. + #[test] + fn an_active_patch_that_declares_anything_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let active = activate(&mut kernel); + let commits_before = kernel.journal.commit_count(); + let declaring = patch_of(vec![entity( + "rhythm-road", + "The Rhythm Road", + EntityKind::Place, + )]); + let bearing_evidence = WorldPatch { + declarations: Vec::new(), + operations: Vec::new(), + evidence: vec![EvidenceRef("run-115".into())], + }; + + for patch in [declaring, bearing_evidence] { + let error = kernel + .submit( + command( + &active, + CommandId::new(), + CallerId::Principal(owner()), + admit(patch), + ), + &auth_principal(owner()), + ) + .unwrap_err(); + // Declaring in Active is elaboration, and elaboration answers a + // boundary. An unanswered one is refused before resolution. + assert!(matches!(error, KernelError::AnswerRequired)); + } + assert_eq!(kernel.journal.commit_count(), commits_before); + assert_eq!(kernel.snapshot().unwrap(), active); + assert_eq!(kernel.state.entities.len(), FIXTURE_ENTITIES); + } + + /// Three places whose containers form a cycle name themselves, and the + /// unrelated empty label joins the same complete set. + #[test] + fn a_containment_cycle_is_rejected_with_the_complete_set() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let before = kernel.snapshot().unwrap(); + + let error = kernel + .submit( + command( + &before, + CommandId::new(), + CallerId::Principal(owner()), + admit(patch_of(vec![ + contained("yard", "The Cavity Yard", "road"), + contained("road", "The Rhythm Road", "gate"), + contained("gate", "The Rain Gate", "yard"), + entity("orphan", " ", EntityKind::Place), + ])), + ), + &auth_principal(owner()), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + let mut expected = vec![ + Mismatch::ContainmentCycle { + referent: draft("yard"), + }, + Mismatch::ContainmentCycle { + referent: draft("road"), + }, + Mismatch::ContainmentCycle { + referent: draft("gate"), + }, + Mismatch::EmptyLabel { + handle: draft("orphan"), + }, + ]; + expected.sort(); + assert_eq!(mismatches, expected); + assert_eq!(kernel.snapshot().unwrap(), before); + assert_eq!(kernel.state.entities.len(), FIXTURE_ENTITIES); + } + + #[test] + fn a_route_endpoint_that_is_not_a_place_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let before = kernel.snapshot().unwrap(); + + let error = kernel + .submit( + command( + &before, + CommandId::new(), + CallerId::Principal(owner()), + admit(patch_of(vec![ + entity("yard", "The Cavity Yard", EntityKind::Place), + entity("tithe", "The Rhythm Tithe", EntityKind::Resource), + route("ramp", "The Yard Ramp", "yard", "tithe", 12), + ])), + ), + &auth_principal(owner()), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + assert_eq!( + mismatches, + vec![Mismatch::WrongKind { + site: at("ramp"), + referent: RefName::Entity(Ref::Draft(draft("tithe"))), + expected: PLACE, + actual: RefKind::Entity(EntityKind::Resource), + }] + ); + assert!(kernel.state.edges.is_empty()); + assert_eq!(kernel.snapshot().unwrap(), before); + } + + /// One name for one failed check, whether the cost arrives in a declaration + /// or in an operation. + #[test] + fn an_invalid_route_cost_is_rejected_from_declaration_and_from_alter_cost() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let topology = admit_topology(&mut kernel); + let before = kernel.snapshot().unwrap(); + + let error = kernel + .submit( + command( + &before, + CommandId::new(), + CallerId::Principal(owner()), + admit(WorldPatch { + declarations: vec![Declaration::Route(RouteDeclaration { + handle: draft("free-ride"), + label: "The Free Ride".into(), + from: Ref::Existing(topology.yard), + to: Ref::Existing(topology.road), + access: AccessKind::Public, + cost: Cost(0), + })], + operations: vec![ComponentOp::AlterCost { + route: Ref::Existing(topology.ramp), + cost: Cost(MAX_ROUTE_COST + 1), + }], + evidence: Vec::new(), + }), + ), + &auth_principal(owner()), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + let mut expected = vec![ + Mismatch::InvalidCost { + site: at("free-ride"), + }, + Mismatch::InvalidCost { + site: Site::Operation(0), + }, + ]; + expected.sort(); + assert_eq!(mismatches, expected); + assert_eq!(kernel.snapshot().unwrap(), before); + } + + /// Each refusal has exactly one name: a closed route, a restricted one, and + /// a route that does not start where the subject stands. + #[test] + fn relocate_without_an_open_public_route_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let topology = admit_topology(&mut kernel); + let active = activate(&mut kernel); + let commits_before = kernel.journal.commit_count(); + + for (edge_id, expected) in [ + (topology.shutter, Mismatch::RouteClosed { operation: 0 }), + ( + topology.toll, + Mismatch::RouteAccessRestricted { operation: 0 }, + ), + (topology.span, Mismatch::SubjectNotAtOrigin { operation: 0 }), + ] { + let error = kernel + .submit( + command( + &active, + CommandId::new(), + CallerId::Principal(owner()), + admit(operations_of(vec![ComponentOp::Relocate { + subject: Ref::Existing(topology.walker), + via: Ref::Existing(edge_id), + }])), + ), + &auth_principal(owner()), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + assert_eq!(mismatches, vec![expected]); + } + assert_eq!(kernel.journal.commit_count(), commits_before); + assert_eq!(kernel.snapshot().unwrap(), active); + assert_eq!( + kernel.state.positions.get(&topology.walker), + Some(&Position { + place: topology.yard + }) + ); + } + + /// PA.f48: `candidate_effective_authority` is the resolver's twin of + /// `delegated_authority`, and must share its predicate for "is this + /// institution live". Retiring the lending institution and granting the + /// same ground directly to its former office-holder, in one patch, must + /// not be read as an overlap with a lend the retirement already killed. + #[test] + fn a_grant_after_retiring_the_lending_institution_is_admitted() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let (_, civic, before) = civic_world(&mut kernel); + + // The office lends levy over the whole hall; grant the reeve levy + // directly over the chamber the hall contains, so a resolver that + // still counted the dead lend would see two distinct, overlapping + // `GrantKey`s (not one collapsed duplicate) and refuse. + let receipt = submit_owner( + &mut kernel, + &before, + admit(operations_of(vec![ + ComponentOp::Retire { + subject: Ref::Existing(civic.treasury), + }, + grant_to(civic.reeve, LEVY_KIND, over_place(civic.chamber)), + ])), + ); + assert!( + matches!(receipt, SubmitReceipt::Applied(_)), + "a dead institution's lend must not collide with a fresh direct grant over the same ground" + ); + } + + /// PA.f48: a `Relocate` through a restricted route open only through a + /// dead institution's delegated authority is refused by the resolver + /// itself, as an ordinary `RouteAccessRestricted` mismatch — not + /// admitted by the resolver and then blown up as a `KernelError::Invariant` + /// when canonical apply recomputes the same authority, correctly finds it + /// gone, and refuses the already-applied `Retire`'s sibling operation. + #[test] + fn a_relocate_relying_only_on_a_retiring_institutions_authority_is_refused_by_the_resolver() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let (topology, civic, before) = civic_world(&mut kernel); + + // `topology.walker` already exists and already stands at `yard`, so + // this delegation patch is operations-only: no declaration, no + // `AnswerRequired` elaboration boundary to clear. + let delegated = submit_owner( + &mut kernel, + &before, + admit(operations_of(vec![ + grant_to(civic.treasury, ADMIT_KIND, over_place(civic.chamber)), + ComponentOp::OpenOffice { + institution: Ref::Existing(civic.treasury), + office: office("portal"), + delegated: BTreeSet::from([authority_kind(ADMIT_KIND)]), + }, + ComponentOp::InstallIncumbent { + institution: Ref::Existing(civic.treasury), + office: office("portal"), + incumbent: Ref::Existing(topology.walker), + }, + ])), + ); + assert!( + matches!(delegated, SubmitReceipt::Applied(_)), + "expected the delegation patch to apply, got {delegated:?}" + ); + let after_delegation = kernel.snapshot().unwrap(); + + let commits_before = kernel.journal.commit_count(); + let mismatches = reject_owner( + &mut kernel, + &after_delegation, + admit(operations_of(vec![ + ComponentOp::Retire { + subject: Ref::Existing(civic.treasury), + }, + ComponentOp::Relocate { + subject: Ref::Existing(topology.walker), + via: Ref::Existing(civic.postern), + }, + ])), + ); + assert_eq!( + mismatches, + vec![Mismatch::RouteAccessRestricted { operation: 1 }], + "the resolver must refuse the dead institution's lend itself, not let apply blow up" + ); + assert_eq!(kernel.journal.commit_count(), commits_before); + assert_eq!(kernel.snapshot().unwrap(), after_delegation); + } + + #[test] + fn relocate_moves_the_subject_and_nothing_else() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let topology = admit_topology(&mut kernel); + let active = activate(&mut kernel); + let entities_before = kernel.state.entities.clone(); + let edges_before = kernel.state.edges.clone(); + + let receipt = submit_owner( + &mut kernel, + &active, + admit(operations_of(vec![ComponentOp::Relocate { + subject: Ref::Existing(topology.walker), + via: Ref::Existing(topology.ramp), + }])), + ); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert_eq!( + kernel.state.positions.get(&topology.walker), + Some(&Position { + place: topology.road + }) + ); + assert_eq!(kernel.state.entities, entities_before); + assert_eq!(kernel.state.edges, edges_before); + let after = kernel.snapshot().unwrap(); + assert_eq!( + after + .subjects + .iter() + .find(|subject| subject.id == topology.walker) + .expect("the walker is in the snapshot") + .position, + Some(topology.road) + ); + } + + #[test] + fn restart_replay_after_a_relocate_is_exact() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "Kharad"), + &auth_principal(owner()), + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + let active = activate(&mut kernel); + let envelope = command( + &active, + CommandId::new(), + CallerId::Principal(owner()), + admit(operations_of(vec![ComponentOp::Relocate { + subject: Ref::Existing(topology.walker), + via: Ref::Existing(topology.ramp), + }])), + ); + kernel + .submit(envelope.clone(), &auth_principal(owner())) + .unwrap(); + let committed = kernel.snapshot().unwrap(); + let world_id = committed.world_id; + drop(kernel); + + let mut reopened = WorldKernel::open(&path, world_id).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), committed); + assert_eq!( + reopened.state.positions.get(&topology.walker), + Some(&Position { + place: topology.road + }) + ); + assert!(matches!( + reopened.submit(envelope, &auth_principal(owner())).unwrap(), + SubmitReceipt::AlreadyApplied(_) + )); + } + + #[test] + fn the_snapshot_exposes_places_routes_and_positions_deterministically() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let topology = admit_topology(&mut kernel); + let snapshot = kernel.snapshot().unwrap(); + assert_eq!(snapshot, kernel.snapshot().unwrap()); + + assert_eq!(snapshot.places.len(), 4); + let place_ids: Vec<_> = snapshot.places.iter().map(|place| place.id).collect(); + let mut sorted_places = place_ids.clone(); + sorted_places.sort(); + assert_eq!(place_ids, sorted_places); + assert!(place_ids.contains(&topology.gate)); + + assert_eq!(snapshot.routes.len(), 4); + let route_ids: Vec<_> = snapshot.routes.iter().map(|route| route.id).collect(); + let mut sorted_routes = route_ids.clone(); + sorted_routes.sort(); + assert_eq!(route_ids, sorted_routes); + let shutter = snapshot + .routes + .iter() + .find(|route| route.id == topology.shutter) + .expect("the shutter is in the snapshot"); + assert!(!shutter.open); + assert_eq!(shutter.cost, Cost(5)); + assert_eq!(shutter.from, topology.yard); + + for subject in &snapshot.subjects { + assert_eq!( + subject.position, + kernel + .state + .positions + .get(&subject.id) + .map(|position| position.place) + ); + } + } + + #[test] + fn admit_patch_from_a_non_owner_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let before = kernel.snapshot().unwrap(); + let commits_before = kernel.journal.commit_count(); + + let error = kernel + .submit( + command( + &before, + CommandId::new(), + CallerId::Principal(human_principal()), + admit(patch_of(vec![entity( + "rhythm-road", + "The Rhythm Road", + EntityKind::Place, + )])), + ), + &auth_principal(human_principal()), + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Unauthorized)); + assert_eq!(kernel.journal.commit_count(), commits_before); + assert_eq!(kernel.snapshot().unwrap(), before); + } + + #[test] + fn restart_replay_after_a_committed_patch_is_exact() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "Kharad"), + &auth_principal(owner()), + ) + .unwrap(); + let before = kernel.snapshot().unwrap(); + let envelope = command( + &before, + CommandId::new(), + CallerId::Principal(owner()), + admit(patch_of(vec![ + entity("rhythm-road", "The Rhythm Road", EntityKind::Place), + institution( + &kernel, + "rhythm-authority", + "The Rhythm Authority", + Some(Ref::Draft(DraftHandle::new("rhythm-road"))), + ), + ])), + ); + kernel + .submit(envelope.clone(), &auth_principal(owner())) + .unwrap(); + let committed = kernel.snapshot().unwrap(); + let world_id = committed.world_id; + drop(kernel); + + let mut reopened = WorldKernel::open(&path, world_id).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), committed); + assert!(matches!( + reopened.submit(envelope, &auth_principal(owner())).unwrap(), + SubmitReceipt::AlreadyApplied(_) + )); + } + + /// One allocator, a pure function of `(world_id, command_id, handle)`: the + /// same handle text under two commands gets two IDs, and the same command + /// re-resolved gets the same ones. + #[test] + fn genesis_and_admit_patch_share_one_allocator() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let before = kernel.snapshot().unwrap(); + let genesis_human = before + .subjects + .iter() + .find(|subject| subject.label == "The Human") + .expect("the genesis human subject") + .id; + + let patch = patch_of(vec![Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("human"), + label: "Another Human".into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + affordances: BTreeSet::from([speak_entry(&kernel)]), + position: None, + import_key: None, + })]); + submit_owner(&mut kernel, &before, admit(patch.clone())); + let admitted = *kernel + .state + .subjects + .iter() + .find(|(_, subject)| subject.label == "Another Human") + .expect("the admitted subject") + .0; + assert_ne!(admitted, genesis_human); + + let command_id = CommandId::new(); + let first = resolve_patch(&kernel.state, command_id, &patch, None, None).unwrap(); + let second = resolve_patch(&kernel.state, command_id, &patch, None, None).unwrap(); + assert_eq!(first, second); + } + + /// The durable half of "a rejected patch mints nothing": the store on disk, + /// not just the in-memory head, carries no row and no byte of any ID the + /// rejected patch would have allocated. + #[test] + fn a_rejected_patch_leaves_no_row_and_no_id_in_the_store() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "Kharad"), + &auth_principal(owner()), + ) + .unwrap(); + let before = kernel.snapshot().unwrap(); + let command_id = CommandId::new(); + let handle = DraftHandle::new("rhythm-authority"); + + let error = kernel + .submit( + command( + &before, + command_id, + CallerId::Principal(owner()), + admit(patch_of(vec![institution( + &kernel, + "rhythm-authority", + "The Rhythm Authority", + Some(Ref::Draft(DraftHandle::new("kharad-rhythm-road"))), + )])), + ), + &auth_principal(owner()), + ) + .unwrap_err(); + assert!(matches!(error, KernelError::PatchRejected(_))); + + // Every ID the patch would have allocated, had resolution closed. + let would_be = [ + derive_id( + SUBJECT_NAMESPACE, + before.world_id, + command_id, + &handle, + None, + ), + derive_id( + CONTROLLER_NAMESPACE, + before.world_id, + command_id, + &handle, + None, + ), + derive_id( + AFFORDANCE_NAMESPACE, + before.world_id, + command_id, + &handle, + Some("speak"), + ), + ]; + + drop(kernel); + let raw = std::fs::read(&path).unwrap(); + for id in would_be { + assert!( + !raw.windows(16).any(|window| window == id.as_bytes()), + "a rejected patch left {id} in the store" + ); + } + + let reopened = WorldKernel::open(&path, before.world_id).unwrap(); + assert_eq!(reopened.snapshot().unwrap(), before); + assert_eq!(reopened.journal.commit_count(), 1); + assert_eq!(reopened.state.entities.len(), FIXTURE_ENTITIES); + assert!( + !reopened + .state + .subjects + .contains_key(&SubjectId(would_be[0])) + ); + } + + /// `discriminator` is length-prefixed like `handle`, so `Some("")` and + /// `None` write different bytes into the preimage and cannot collide — + /// and neither can any other pair of discriminators whose bytes would + /// otherwise concatenate to the same string. + #[test] + fn derive_id_does_not_collide_some_empty_discriminator_with_none() { + let directory = tempfile::tempdir().unwrap(); + let (kernel, _) = WorldKernel::create( + &directory.path().join("world.cc"), + creation(CommandId::new(), "DeriveId"), + &auth_principal(owner()), + ) + .unwrap(); + let world_id = kernel.state.world_id; + let command_id = CommandId::new(); + let handle = DraftHandle::new("a-handle"); + assert_ne!( + derive_id(SUBJECT_NAMESPACE, world_id, command_id, &handle, None), + derive_id(SUBJECT_NAMESPACE, world_id, command_id, &handle, Some("")), + ); + // A concatenation-style collision across the handle/discriminator + // boundary: without a length prefix on the discriminator, "ab" + "" + // and "a" + "b" would hash identically. + assert_ne!( + derive_id( + SUBJECT_NAMESPACE, + world_id, + command_id, + &DraftHandle::new("ab"), + Some(""), + ), + derive_id( + SUBJECT_NAMESPACE, + world_id, + command_id, + &DraftHandle::new("a"), + Some("b"), + ), + ); + } + + /// The `PatchAdmitted` arm is not a trusting applier. A forged effect, a + /// replayed one, a non-owner caller, and the Active phase each die inside + /// `apply_effect`, without the journal's reduce-equality check running. + #[test] + fn apply_effect_rejects_a_forged_stale_unauthorized_or_active_patch_effect() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let before = kernel.snapshot().unwrap(); + let patch = patch_of(vec![ + entity("rhythm-road", "The Rhythm Road", EntityKind::Place), + institution( + &kernel, + "rhythm-authority", + "The Rhythm Authority", + Some(Ref::Draft(DraftHandle::new("rhythm-road"))), + ), + ]); + let resolved = resolve_patch(&kernel.state, CommandId::new(), &patch, None, None).unwrap(); + let honest = super::super::WorldEffect::PatchAdmitted { + resolved: resolved.clone(), + answers: None, + }; + + // Forged: the position names a place no partition holds, and the effect + // no longer carries the entity that would have created it. + let mut forged = resolved.clone(); + forged.entities.clear(); + forged.subjects[0].position = Some(Position { + place: super::super::EntityId::issue(), + }); + let mut candidate = kernel.state.clone(); + let forged_error = super::super::apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Principal(owner()), + &super::super::WorldEffect::PatchAdmitted { + answers: None, + resolved: forged, + }, + ) + .unwrap_err(); + assert!(matches!(forged_error, KernelError::Invariant(_))); + + // Stale: the honest effect applied twice collides on its own IDs. + let mut candidate = kernel.state.clone(); + super::super::apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Principal(owner()), + &honest, + ) + .unwrap(); + let stale_error = super::super::apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Principal(owner()), + &honest, + ) + .unwrap_err(); + assert!(matches!(stale_error, KernelError::Invariant(_))); + + // A non-owner caller never reaches admission. + let mut candidate = kernel.state.clone(); + let unauthorized = super::super::apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Principal(human_principal()), + &honest, + ) + .unwrap_err(); + assert!(matches!(unauthorized, KernelError::Invariant(_))); + assert_eq!(candidate, kernel.state); + + // And an unanswered declaring effect is refused in Active before any + // partition is touched. + let active = activate(&mut kernel); + assert_eq!(active.revision, before.revision + 3); + let mut candidate = kernel.state.clone(); + let unanswered = super::super::apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Principal(owner()), + &honest, + ) + .unwrap_err(); + assert!(matches!(unanswered, KernelError::AnswerRequired)); + assert_eq!(candidate, kernel.state); + } + + /// Soul falsification: the three pass-2 `Mismatch` variants that no landed + /// test names are each reachable from a real patch. + #[test] + fn soul_self_loop_unplaced_subject_and_no_effect_are_each_reachable() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let before = kernel.snapshot().unwrap(); + + // A route whose two endpoints resolve to one place. + let error = kernel + .submit( + command( + &before, + CommandId::new(), + CallerId::Principal(owner()), + admit(patch_of(vec![ + entity("hollow", "The Hollow", EntityKind::Place), + route("noose", "The Noose", "hollow", "hollow", 4), + ])), + ), + &auth_principal(owner()), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + assert_eq!( + mismatches, + vec![Mismatch::RouteSelfLoop { + referent: draft("noose") + }] + ); + + let topology = admit_topology(&mut kernel); + // Every fixture subject stands somewhere now, so the unplaced case is + // declared here rather than borrowed from a genesis accident. + let before = kernel.snapshot().unwrap(); + let speak = speak_entry(&kernel); + submit_owner( + &mut kernel, + &before, + admit(patch_of(vec![Declaration::Subject(SubjectDeclaration { + handle: draft("nowhere"), + label: "The Unplaced".into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + affordances: BTreeSet::from([speak]), + position: None, + import_key: None, + })])), + ); + let active = activate(&mut kernel); + let commits_before = kernel.journal.commit_count(); + let unplaced = *kernel + .state + .subjects + .iter() + .find(|(subject_id, _)| !kernel.state.positions.contains_key(*subject_id)) + .expect("the unplaced subject this test declared") + .0; + + // Relocating a subject that stands nowhere. + let error = kernel + .submit( + command( + &active, + CommandId::new(), + CallerId::Principal(owner()), + admit(operations_of(vec![ComponentOp::Relocate { + subject: Ref::Existing(unplaced), + via: Ref::Existing(topology.ramp), + }])), + ), + &auth_principal(owner()), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + assert_eq!(mismatches, vec![Mismatch::UnplacedSubject { operation: 0 }]); + + // Three operations that each change nothing: the ramp is already open, + // the shutter already closed, and the ramp already costs twelve. + let error = kernel + .submit( + command( + &active, + CommandId::new(), + CallerId::Principal(owner()), + admit(operations_of(vec![ + ComponentOp::OpenRoute { + route: Ref::Existing(topology.ramp), + }, + ComponentOp::CloseRoute { + route: Ref::Existing(topology.shutter), + }, + ComponentOp::AlterCost { + route: Ref::Existing(topology.ramp), + cost: Cost(12), + }, + ])), + ), + &auth_principal(owner()), + ) + .unwrap_err(); + let KernelError::PatchRejected(mismatches) = error else { + panic!("expected a rejected patch"); + }; + assert_eq!( + mismatches, + vec![ + Mismatch::NoOperationEffect { operation: 0 }, + Mismatch::NoOperationEffect { operation: 1 }, + Mismatch::NoOperationEffect { operation: 2 }, + ] + ); + assert_eq!(kernel.snapshot().unwrap(), active); + assert_eq!(kernel.journal.commit_count(), commits_before); + } + + /// Soul falsification: `admit_resolved` re-derives every relocate + /// precondition, so a forged effect naming a route the subject does not + /// stand on, a closed route, or a restricted one dies at apply time. + #[test] + fn soul_a_forged_relocate_effect_is_refused_at_apply_time() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let topology = admit_topology(&mut kernel); + activate(&mut kernel); + for edge_id in [topology.span, topology.shutter, topology.toll] { + let forged = super::super::WorldEffect::PatchAdmitted { + resolved: ResolvedPatch { + lens_weights: None, + subjects: Vec::new(), + entities: Vec::new(), + routes: Vec::new(), + affordances: Vec::new(), + facts: Vec::new(), + channels: Vec::new(), + operations: vec![ResolvedOp::Relocate { + subject_id: topology.walker, + edge_id, + }], + evidence: Vec::new(), + scale_intent: None, + }, + answers: None, + }; + let mut candidate = kernel.state.clone(); + let error = super::super::apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Principal(owner()), + &forged, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_))); + assert_eq!(candidate, kernel.state); + } + } +} diff --git a/native/aetherlight/tests/fixtures/base_world.cc b/native/aetherlight/tests/fixtures/base_world.cc new file mode 100644 index 000000000..d4c8eadac Binary files /dev/null and b/native/aetherlight/tests/fixtures/base_world.cc differ diff --git a/native/aetherlight/tests/fixtures/base_world.digests b/native/aetherlight/tests/fixtures/base_world.digests new file mode 100644 index 000000000..ab9edc3ea --- /dev/null +++ b/native/aetherlight/tests/fixtures/base_world.digests @@ -0,0 +1,3 @@ +3 +sha256:b706f57cb417603366a1f47a5dd099fbf68bfecc5b2e8d61d281630791d1d76d +sha256:2039956a26c3d5b073d101e5898ac5a60a9eb63a3b93f447b2d8f78ef4caf979 diff --git a/native/aetherlight/tests/fixtures/base_world.id b/native/aetherlight/tests/fixtures/base_world.id new file mode 100644 index 000000000..f23316a4c --- /dev/null +++ b/native/aetherlight/tests/fixtures/base_world.id @@ -0,0 +1 @@ +"a534b32a-4d00-429c-bf6c-ce1d55385380"