Compare commits

..
Author SHA1 Message Date
491fc2020f Thing 2.0: state port values (StateValue, Record::State) and thing-state's by-name decode (#12)
All checks were successful
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (push) Successful in 3m30s
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (push) Successful in 3m37s
2026-11-28 02:05:00 +00:00
b1c007d8b1 Thing 2.0: CultLib pin to 4c9af401 (member rows), whole-value contract lists, resolve on any thread (#11)
Some checks failed
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (push) Has been cancelled
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (push) Has been cancelled
2026-11-28 01:26:23 +00:00
edeeee2129 Thing 2.0 cut 3: resolve (pure expansion, closed diagnostics, thing.std stat and card) (#10)
All checks were successful
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (push) Successful in 3m25s
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (push) Successful in 3m22s
2026-11-27 23:50:18 +00:00
e16a8eb917 Thing contract: Slot node, arm 13, in Rust, C# and TypeScript (thing2:ruling:composition-slot-node) (#9)
All checks were successful
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (push) Successful in 2m37s
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (push) Successful in 2m13s
2026-11-27 22:27:17 +00:00
4d254a1adf Thing 2.0: the remaining fixtures (testkit-fixtures) (#8)
All checks were successful
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (push) Successful in 2m43s
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (push) Successful in 1m43s
2026-11-27 20:52:51 +00:00
31f324f738 Thing contract, TypeScript: @gamecult/thing-contract (thing2 cut 1a) (#6)
Some checks failed
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (push) Has been cancelled
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (push) Has been cancelled
2026-11-27 20:43:02 +00:00
d052428094 Thing 2.0 cut 2: thing-core state port and thing-testkit (testkit-ports) (#7)
Some checks failed
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (push) Has been cancelled
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (push) Has been cancelled
2026-11-27 20:29:51 +00:00
7654e27364 Thing contract, C#: GameCult.Thing.Contract (thing2 cut 1b) (#5)
All checks were successful
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (push) Successful in 6m56s
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (push) Successful in 3m20s
2026-11-27 17:54:25 +00:00
159ad486e5 Merge pull request 'Thing 2.0 build spec (Meta t12-m0)' (#1) from libby/thing2-build-spec into main
All checks were successful
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (push) Successful in 3m29s
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (push) Successful in 2m57s
2026-11-11 00:20:06 +00:00
Libby
b6e06cf89a thing2 build spec: drop Brokkr gap, point site gap at Void, remove unsupported status claims
All checks were successful
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (pull_request) Successful in 3m6s
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (pull_request) Successful in 3m46s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-10 23:18:13 +00:00
Libby
366774dc4c thing2 build spec: mark union-parity follow-up resolved
Some checks failed
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (pull_request) Has been cancelled
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (pull_request) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-10 23:16:57 +00:00
Libby
9eb099be4d thing2 build spec: refresh against rulings in force
Some checks failed
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (pull_request) Has been cancelled
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (pull_request) Has been cancelled
Cite code-home, port-cutover, compat-rebuild, freeze-fold, owns-text,
quarantine and frozen-surface rulings; note site and Brokkr port gaps;
close O11/O13 and the substrate-gap note; map pointer to r3 specs.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-10 23:16:46 +00:00
Libby
3136ee8b80 Merge remote-tracking branch 'origin/main' into libby/thing2-build-spec
All checks were successful
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (pull_request) Successful in 2m2s
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (pull_request) Successful in 2m35s
2026-11-10 17:40:51 +00:00
fd7a48484d CI: concurrency group, no cancel on dispatch (#4)
All checks were successful
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (push) Successful in 3m11s
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (push) Successful in 2m17s
2026-11-10 17:40:14 +00:00
4a6c04a073 CI: Windows leg workflow_dispatch only, PowerShell on Linux (#2)
Some checks failed
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (push) Successful in 3m12s
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (push) Failing after 36s
2026-11-09 23:24:35 +00:00
Libby
ee8eec41f3 thing2 build spec: reconcile with rulings read from the eureka mind
Some checks failed
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (pull_request) Has been cancelled
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (pull_request) Has been cancelled
Portable Eve contracts and browser lowering / windows-latest eve-browser-lowering (pull_request) Has been cancelled
Portable Eve contracts and browser lowering / windows-latest eve-contracts (pull_request) Has been cancelled
decode-stack-safety is Fixed (CultLib bbb98eaf); contract-ts/cs specs are r3;
discovery reads the eve advertisement through a port until its owner lands;
O11 tooling wording follows the thing-script-form question.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 10:35:43 +00:00
Libby
ebafda432f thing2 build spec: reconcile O11 with thing-script-form ruling
Some checks failed
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (pull_request) Has been cancelled
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (pull_request) Has been cancelled
Portable Eve contracts and browser lowering / windows-latest eve-browser-lowering (pull_request) Has been cancelled
Portable Eve contracts and browser lowering / windows-latest eve-contracts (pull_request) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 10:33:06 +00:00
Libby
e95f1ab5ba Thing 2.0 build spec: per-piece contracts, build order, tests, prior art
Some checks failed
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (pull_request) Has been cancelled
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (pull_request) Has been cancelled
Portable Eve contracts and browser lowering / windows-latest eve-browser-lowering (pull_request) Has been cancelled
Portable Eve contracts and browser lowering / windows-latest eve-contracts (pull_request) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 07:41:49 +00:00
Libby
0ba536eec1 research: swarm dashboard sources and first cut
Some checks failed
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (push) Has been cancelled
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (push) Has been cancelled
Portable Eve contracts and browser lowering / windows-latest eve-browser-lowering (push) Has been cancelled
Portable Eve contracts and browser lowering / windows-latest eve-contracts (push) Has been cancelled
Thing 2 contract state, Run/heartbeat/usage-readout sources, and the
smallest first cut for "is anyone working, and on what".

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-31 06:17:41 +00:00
Meta Vens
e119e76301 Merge readme-front-door: README front door
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 19:59:26 +02:00
Meta Vens
afe05b0c7e README front door: entry points and live/planned up front; drop absent relay command and config, repo-relative paths
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 19:55:21 +02:00
Meta Vens
2467e1b025 thing2 map: contract-cs and contract-ts r2 (body facts P20-P22, waiting lines, rationale)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 08:24:39 +02:00
128 changed files with 17636 additions and 125 deletions

View file

@ -8,6 +8,11 @@ on:
pull_request: pull_request:
workflow_dispatch: workflow_dispatch:
concurrency:
# A newer push or PR update replaces the older run on the same ref; workflow_dispatch runs are never cancelled.
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.event_name != 'workflow_dispatch' }}
jobs: jobs:
contracts-and-browser: contracts-and-browser:
name: ${{ matrix.os }} ${{ matrix.package }} name: ${{ matrix.os }} ${{ matrix.package }}
@ -16,7 +21,10 @@ jobs:
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
os: [windows-latest, ubuntu-latest] # No Windows runner exists: the windows-latest leg runs on workflow_dispatch only (GitHub or a
# Windows runner), the ubuntu-latest leg gates push and PR. Windows push/PR triggers return in the PR
# that registers a Windows runner.
os: ${{ fromJSON(github.event_name == 'workflow_dispatch' && '["windows-latest", "ubuntu-latest"]' || '["ubuntu-latest"]') }}
package: [eve-contracts, eve-browser-lowering] package: [eve-contracts, eve-browser-lowering]
steps: steps:
@ -30,6 +38,14 @@ jobs:
cache: npm cache: npm
cache-dependency-path: packages/${{ matrix.package }}/package-lock.json cache-dependency-path: packages/${{ matrix.package }}/package-lock.json
# eve-browser-lowering links eve-contracts as file:../eve-contracts; npm installs none of the
# linked package's dependencies, and tsc resolves its declarations from the real path, so
# ajv must be installed in eve-contracts itself.
- name: Install eve-contracts dependencies
if: matrix.package != 'eve-contracts'
working-directory: packages/eve-contracts
run: npm ci
- name: Install package dependencies - name: Install package dependencies
working-directory: packages/${{ matrix.package }} working-directory: packages/${{ matrix.package }}
run: npm ci run: npm ci
@ -38,6 +54,23 @@ jobs:
working-directory: packages/${{ matrix.package }} working-directory: packages/${{ matrix.package }}
run: npm test run: npm test
# The forge runner images carry no pwsh; GitHub's Windows and hosted images do.
- name: Install PowerShell
if: runner.os == 'Linux'
shell: bash
run: |
set -euo pipefail
if command -v pwsh >/dev/null; then pwsh -Version; exit 0; fi
SUDO=""; [ "$(id -u)" -eq 0 ] || SUDO="sudo"
PWSH_VERSION=7.4.6
curl -fsSL "https://github.com/PowerShell/PowerShell/releases/download/v${PWSH_VERSION}/powershell-${PWSH_VERSION}-linux-x64.tar.gz" -o "${RUNNER_TEMP:-/tmp}/powershell.tar.gz"
$SUDO mkdir -p /opt/microsoft/powershell/7
$SUDO tar -xzf "${RUNNER_TEMP:-/tmp}/powershell.tar.gz" -C /opt/microsoft/powershell/7
$SUDO chmod +x /opt/microsoft/powershell/7/pwsh
$SUDO ln -sf /opt/microsoft/powershell/7/pwsh /usr/local/bin/pwsh
echo "DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1" >> "$GITHUB_ENV"
DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1 pwsh -Version
- name: Reject stale generated output - name: Reject stale generated output
shell: pwsh shell: pwsh
run: | run: |

7
.gitignore vendored
View file

@ -8,12 +8,19 @@ packages/eve-browser-lowering/node_modules/
!packages/eve-contracts/** !packages/eve-contracts/**
packages/eve-contracts/node_modules/ packages/eve-contracts/node_modules/
packages/eve-contracts/*.tgz packages/eve-contracts/*.tgz
!packages/thing-contract/
!packages/thing-contract/**
packages/thing-contract/node_modules/
packages/thing-contract/dist/
packages/thing-contract/dist-test/
!packages/org.gamecult.eve.surface/ !packages/org.gamecult.eve.surface/
!packages/org.gamecult.eve.surface/** !packages/org.gamecult.eve.surface/**
packages/org.gamecult.eve.surface/bin~/ packages/org.gamecult.eve.surface/bin~/
packages/org.gamecult.eve.surface/obj~/ packages/org.gamecult.eve.surface/obj~/
!packages/org.gamecult.eve.unity-uitoolkit/ !packages/org.gamecult.eve.unity-uitoolkit/
!packages/org.gamecult.eve.unity-uitoolkit/** !packages/org.gamecult.eve.unity-uitoolkit/**
!packages/GameCult.Thing.Contract/
!packages/GameCult.Thing.Contract/**
obj/ obj/
artifacts/ artifacts/
tools/deps/ tools/deps/

178
Cargo.lock generated
View file

@ -17,12 +17,30 @@ version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
[[package]]
name = "ar_archive_writer"
version = "0.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "523e5e187fff36fcb8d1d19ccf0ca4ca43ec3d158316057f66dc6f72716bc5ec"
dependencies = [
"object",
]
[[package]] [[package]]
name = "autocfg" name = "autocfg"
version = "1.5.1" version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "block-buffer"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
dependencies = [
"generic-array",
]
[[package]] [[package]]
name = "bumpalo" name = "bumpalo"
version = "3.20.3" version = "3.20.3"
@ -65,10 +83,29 @@ version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" 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]] [[package]]
name = "cultcache-rs" name = "cultcache-rs"
version = "0.2.0" version = "0.3.1"
source = "git+https://github.com/GameCult/CultLib.git?rev=b3bd8dd5e5b208b2012392e9c5d6dfee2441aaa7#b3bd8dd5e5b208b2012392e9c5d6dfee2441aaa7" source = "git+https://github.com/GameCult/CultLib.git?rev=4c9af401ae33812d862dde4ff3131433fc73c7dc#4c9af401ae33812d862dde4ff3131433fc73c7dc"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"chrono", "chrono",
@ -79,20 +116,33 @@ dependencies = [
"serde", "serde",
"serde_bytes", "serde_bytes",
"serde_json", "serde_json",
"serde_stacker",
"sha2",
"stacker",
"uuid", "uuid",
"windows-sys", "windows-sys 0.59.0",
] ]
[[package]] [[package]]
name = "cultcache-rs-derive" name = "cultcache-rs-derive"
version = "0.1.0" version = "0.2.0"
source = "git+https://github.com/GameCult/CultLib.git?rev=b3bd8dd5e5b208b2012392e9c5d6dfee2441aaa7#b3bd8dd5e5b208b2012392e9c5d6dfee2441aaa7" source = "git+https://github.com/GameCult/CultLib.git?rev=4c9af401ae33812d862dde4ff3131433fc73c7dc#4c9af401ae33812d862dde4ff3131433fc73c7dc"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.119", "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]] [[package]]
name = "find-msvc-tools" name = "find-msvc-tools"
version = "0.1.14" version = "0.1.14"
@ -133,6 +183,16 @@ dependencies = [
"slab", "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]] [[package]]
name = "getrandom" name = "getrandom"
version = "0.4.3" version = "0.4.3"
@ -212,6 +272,15 @@ dependencies = [
"autocfg", "autocfg",
] ]
[[package]]
name = "object"
version = "0.39.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b"
dependencies = [
"memchr",
]
[[package]] [[package]]
name = "once_cell" name = "once_cell"
version = "1.21.4" version = "1.21.4"
@ -233,6 +302,16 @@ dependencies = [
"unicode-ident", "unicode-ident",
] ]
[[package]]
name = "psm"
version = "0.1.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622"
dependencies = [
"ar_archive_writer",
"cc",
]
[[package]] [[package]]
name = "quote" name = "quote"
version = "1.0.47" version = "1.0.47"
@ -335,6 +414,28 @@ dependencies = [
"zmij", "zmij",
] ]
[[package]]
name = "serde_stacker"
version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d4936375d50c4be7eff22293a9344f8e46f323ed2b3c243e52f89138d9bb0f4a"
dependencies = [
"serde",
"serde_core",
"stacker",
]
[[package]]
name = "sha2"
version = "0.10.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]] [[package]]
name = "shlex" name = "shlex"
version = "2.0.1" version = "2.0.1"
@ -347,6 +448,19 @@ version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
[[package]]
name = "stacker"
version = "0.1.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967"
dependencies = [
"cc",
"cfg-if",
"libc",
"psm",
"windows-sys 0.61.2",
]
[[package]] [[package]]
name = "syn" name = "syn"
version = "2.0.119" version = "2.0.119"
@ -378,8 +492,47 @@ dependencies = [
"rmp-serde", "rmp-serde",
"serde", "serde",
"serde_bytes", "serde_bytes",
"thing-testkit",
] ]
[[package]]
name = "thing-core"
version = "0.1.0"
dependencies = [
"stacker",
"thing-contract",
"thing-testkit",
]
[[package]]
name = "thing-state"
version = "0.1.0"
dependencies = [
"cultcache-rs",
"rmp-serde",
"serde",
"thing-core",
]
[[package]]
name = "thing-testkit"
version = "0.1.0"
dependencies = [
"anyhow",
"cultcache-rs",
"rmp-serde",
"serde",
"thing-contract",
"thing-core",
"thing-state",
]
[[package]]
name = "typenum"
version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]] [[package]]
name = "unicode-ident" name = "unicode-ident"
version = "1.0.26" version = "1.0.26"
@ -397,6 +550,12 @@ dependencies = [
"wasm-bindgen", "wasm-bindgen",
] ]
[[package]]
name = "version_check"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]] [[package]]
name = "wasm-bindgen" name = "wasm-bindgen"
version = "0.2.129" version = "0.2.129"
@ -532,6 +691,15 @@ dependencies = [
"windows-targets", "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]] [[package]]
name = "windows-targets" name = "windows-targets"
version = "0.52.6" version = "0.52.6"

View file

@ -4,6 +4,6 @@ resolver = "2"
[workspace.dependencies] [workspace.dependencies]
anyhow = "1" anyhow = "1"
cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "b3bd8dd5e5b208b2012392e9c5d6dfee2441aaa7", package = "cultcache-rs" } cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "4c9af401ae33812d862dde4ff3131433fc73c7dc", package = "cultcache-rs" }
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
rmp-serde = "1.3" rmp-serde = "1.3"

View file

@ -1,9 +1,41 @@
# Thing # Thing
This repository is Thing. Its present tree is Thing 1, kept running for live This repository is Thing (the Eve display, control and sensor edge for GameCult
consumers until each ports; Thing 2.0 is built here (`docs/thing2-target.md`). apps). Its present tree is Thing 1, kept running for live consumers until each
The Thing 1 renderer repos are archived under their Eve names: EveUnity, ports; Thing 2.0 is built here (`docs/thing2-target.md`). The Thing 1 renderer
EveFlutter, EveElectron, EveTui, EvePlugins and EveConformance. repos are archived under their Eve names: EveUnity, EveFlutter, EveElectron,
EveTui, EvePlugins and EveConformance.
## Start Here
Value: services publish a surface once, as a typed retained document
(`gamecult.eve.surface.v1`), and every runtime lowers it locally. Providers keep
authority over state and commands; Eve owns projection, input capture and
timestamped sensor publication.
Problem: without a shared surface contract, each service hand-builds its own
dashboard and each renderer re-implements layout, binding and commands.
Live (Thing 1):
- `packages/org.gamecult.eve.surface`: renderer-neutral C# surface contract and
composition builders; tests in `tests/GameCult.Eve.Surface.Serialization.Tests`.
- `packages/eve-contracts`: TypeScript types and validators generated from
`schemas/` (`npm run generate`, `npm test`).
- `packages/eve-browser-lowering`: browser DOM/CSS lowering of surface documents
(`npm test`).
- `web/`: browser reference oracle (`web/index.html`, `web/eve-dsl.js`; tests
with `node --test web/eve-dsl.test.mjs`).
- `docs/surface-contract-v1.md`: the contract. `docs/repo-strategy.md`: repo
ownership. `docs/parity-testing-harness.md` with
`scripts/run-parity-harness.ps1`: parity runs.
- `android/` and `Sources/` (iOS Theos app, `make package`): native proof
clients; build steps under Build Shape below.
Planned (Thing 2.0, in progress): `crates/thing-contract` is the first Rust
piece. The layout solver, text, accessibility tree, closed render-command list
and thin backends described in `docs/thing2-target.md` and `docs/thing2-map.md`
are not built yet; `docs/thing-campaign.md` holds the rename plan.
CultMesh-based surface web, portable control layer, and timestamped sensor CultMesh-based surface web, portable control layer, and timestamped sensor
edge. edge.
@ -214,11 +246,8 @@ render:
## VoidBot CEF Stream ## VoidBot CEF Stream
Start the Starfire relay from `E:\Projects\VoidBot`: The CEF relay that produced these frames is not in VoidBot's default branch, so
no relay command is documented here until one exists.
```powershell
npm run swarm:eve-cef-relay -- --width 1620 --height 2160 --scale 2 --port 8792
```
EveCanvas displays binary JPEG frames and returns touch events only when a EveCanvas displays binary JPEG frames and returns touch events only when a
stream lowering is configured through `EVE_STREAM_URLS`. The native app no stream lowering is configured through `EVE_STREAM_URLS`. The native app no
@ -226,12 +255,11 @@ longer guesses a Starfire relay address.
## Mimir Sensor Uplink ## Mimir Sensor Uplink
Start Mimir with `config/mimir-runtime.raven-eve.example.json` or run the Run the receiver processes from a Mimir checkout (a sibling `..\Mimir` here):
receiver processes directly:
```powershell ```powershell
dotnet run --project E:\Projects\Mimir\src\Mimir.EveSensorReceiver\Mimir.EveSensorReceiver.csproj -- --port 8793 --path /eve/camera --source-id eve-camera --type video-frame dotnet run --project ..\Mimir\src\Mimir.EveSensorReceiver\Mimir.EveSensorReceiver.csproj -- --port 8793 --path /eve/camera --source-id eve-camera --type video-frame
dotnet run --project E:\Projects\Mimir\src\Mimir.EveSensorReceiver\Mimir.EveSensorReceiver.csproj -- --port 8794 --path /eve/mic --source-id eve-mic --type audio-block dotnet run --project ..\Mimir\src\Mimir.EveSensorReceiver\Mimir.EveSensorReceiver.csproj -- --port 8794 --path /eve/mic --source-id eve-mic --type audio-block
``` ```
EveCanvas sends binary `mimir.eve_media_observation.v1` camera and microphone EveCanvas sends binary `mimir.eve_media_observation.v1` camera and microphone
@ -245,7 +273,7 @@ guess receiver URLs.
Start the dashboard authority on Starfire: Start the dashboard authority on Starfire:
```powershell ```powershell
dotnet run --project E:\Projects\Mimir\src\Mimir.EveDashboard\Mimir.EveDashboard.csproj -- --port 8795 dotnet run --project ..\Mimir\src\Mimir.EveDashboard\Mimir.EveDashboard.csproj -- --port 8795
``` ```
EveCanvas connects to the Mimir dashboard WebSocket lowering for native retained EveCanvas connects to the Mimir dashboard WebSocket lowering for native retained

View file

@ -12,4 +12,5 @@ serde = { workspace = true }
serde_bytes = "0.11" serde_bytes = "0.11"
[dev-dependencies] [dev-dependencies]
thing-testkit = { path = "../thing-testkit" }
rmp-serde = { workspace = true } rmp-serde = { workspace = true }

View file

@ -28,7 +28,7 @@ pub struct AssetCatalog {
pub catalog_id: Segment, pub catalog_id: Segment,
#[cultcache(key = 2)] #[cultcache(key = 2)]
pub version: Version, pub version: Version,
#[cultcache(key = 3)] #[cultcache(key = 3, type_name = "System.Collections.Immutable.ImmutableArray<GameCult.Thing.Contract.AssetEntry>")]
pub assets: Vec<AssetEntry>, pub assets: Vec<AssetEntry>,
} }

View file

@ -37,6 +37,7 @@ pub enum CommandRef {
/// A typed record of the declared `payload_schema`, as its MessagePack bytes. /// A typed record of the declared `payload_schema`, as its MessagePack bytes.
#[derive(Clone, Debug, PartialEq, CultSlots)] #[derive(Clone, Debug, PartialEq, CultSlots)]
#[cultcache(type_name = "GameCult.Thing.Contract.RecordPayload")]
pub struct RecordPayload { pub struct RecordPayload {
#[cultcache(key = 0)] #[cultcache(key = 0)]
pub schema: SchemaId, pub schema: SchemaId,
@ -105,7 +106,7 @@ pub struct CommandInvocation {
pub command: CommandId, pub command: CommandId,
#[cultcache(key = 4)] #[cultcache(key = 4)]
pub payload: RecordPayload, pub payload: RecordPayload,
#[cultcache(key = 5)] #[cultcache(key = 5, type_name = "System.Collections.Immutable.ImmutableArray<GameCult.Thing.Contract.CapturedInput>")]
pub captured: Vec<CapturedInput>, pub captured: Vec<CapturedInput>,
#[cultcache(key = 6)] #[cultcache(key = 6)]
pub client: String, pub client: String,

View file

@ -9,6 +9,7 @@
use std::fmt; use std::fmt;
use cultcache_rs::CultTypeName;
use serde::{Deserialize, Deserializer, Serialize, Serializer, de}; use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
/// A value was outside its domain. Names the domain and its bound, never the value. /// A value was outside its domain. Names the domain and its bound, never the value.
@ -72,6 +73,13 @@ impl std::error::Error for DomainError {}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Seq(i32); pub struct Seq(i32);
impl CultTypeName for Seq {
fn cult_type_name() -> String {
"System.Int32".to_string()
}
const VALUE_TYPE: bool = true;
}
impl Seq { impl Seq {
pub const FIRST: Seq = Seq(1); pub const FIRST: Seq = Seq(1);
@ -108,6 +116,13 @@ impl Seq {
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Version(i64); pub struct Version(i64);
impl CultTypeName for Version {
fn cult_type_name() -> String {
"System.Int64".to_string()
}
const VALUE_TYPE: bool = true;
}
impl Version { impl Version {
pub fn new(value: i64) -> Result<Self, DomainError> { pub fn new(value: i64) -> Result<Self, DomainError> {
if value >= 0 { Ok(Self(value)) } else { Err(DomainError::new("Version", "at least 0")) } if value >= 0 { Ok(Self(value)) } else { Err(DomainError::new("Version", "at least 0")) }
@ -166,6 +181,12 @@ impl Count {
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Segment(String); pub struct Segment(String);
impl CultTypeName for Segment {
fn cult_type_name() -> String {
"System.String".to_string()
}
}
impl Segment { impl Segment {
pub fn new(value: impl Into<String>) -> Result<Self, DomainError> { pub fn new(value: impl Into<String>) -> Result<Self, DomainError> {
let value = value.into(); let value = value.into();

View file

@ -1,5 +1,6 @@
//! Identifier newtypes and the record key of each kind. No caller spells a key as a free string. //! Identifier newtypes and the record key of each kind. No caller spells a key as a free string.
use cultcache_rs::CultTypeName;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::domain::{Segment, Seq, Version}; use crate::domain::{Segment, Seq, Version};
@ -20,6 +21,12 @@ macro_rules! id_type {
&self.0 &self.0
} }
} }
impl CultTypeName for $name {
fn cult_type_name() -> String {
"System.String".to_string()
}
}
}; };
} }

View file

@ -9,10 +9,11 @@
//! field types (`Seq`, `Version`, `Count`, `Segment`), whose `Deserialize` calls the same //! field types (`Seq`, `Version`, `Count`, `Segment`), whose `Deserialize` calls the same
//! `new` the constructors call, so no door skips a check. //! `new` the constructors call, so no door skips a check.
//! //!
//! Hazard: decoding these kinds from untrusted bytes on a default-size thread can abort the //! Stack hazard: `Node` nests without a bound of its own, and serde's `Deserialize` recurses
//! process inside CultCache's nesting bound before the bound refuses (the stack is not //! once per level, so a hostile payload nested deep enough overflows the stack of a caller that
//! bounded by nesting depth). The owner is `cultlib-gaps:follow_up:decode-stack-safety`; the //! decodes it directly. CultCache refuses such a payload on read and on write
//! tests decode on a 16 MiB thread until it lands. //! (`cultcache_rs::check_payload_depth`, 256 containers); a caller that decodes bytes outside a
//! CultCache must run that check first.
mod asset; mod asset;
mod command; mod command;
@ -32,6 +33,7 @@ pub use result::*;
pub use source::*; pub use source::*;
pub use style::*; pub use style::*;
pub use cultcache_rs::DatabaseEntry;
use cultcache_rs::{CultCache, CultCacheRegistry}; use cultcache_rs::{CultCache, CultCacheRegistry};
/// Registers the five kinds with a cache. /// Registers the five kinds with a cache.

View file

@ -1,12 +1,14 @@
//! Thing Script: the closed node union, the surface document that holds a tree of nodes, and the //! Thing Script: the closed node union, the surface document that holds a tree of nodes, and the
//! composition document that names a reusable subtree. Arm keys are fixed for v1. //! composition document that names a reusable subtree. Arm keys are fixed: Slot (13) is the arm
//! added after the first twelve, and a decoder from before it refuses a record holding one
//! (CultCache's unknown-arm rule).
use cultcache_rs::{CultSlots, CultUnion, DatabaseEntry}; use cultcache_rs::{CultSlots, CultUnion, DatabaseEntry};
use crate::domain::{Count, Segment, Version}; use crate::domain::{Count, Segment, Version};
use crate::command::{CommandDecl, CommandRef}; use crate::command::{CommandDecl, CommandRef};
use crate::keys::{NodeId, ProviderId, composition_key, surface_key}; use crate::keys::{NodeId, ProviderId, composition_key, surface_key};
use crate::source::{Bind, BoolSource, CollectionSource, MemberPath, NumberSource, TextSource}; use crate::source::{Bind, BoolSource, CollectionSource, MemberPath, NumberSource, ParamName, TextSource};
use crate::style::{BoxStyle, Paint, Role}; use crate::style::{BoxStyle, Paint, Role};
/// What every node carries. /// What every node carries.
@ -21,6 +23,7 @@ pub struct NodeCommon {
} }
#[derive(Clone, Debug, PartialEq, CultUnion)] #[derive(Clone, Debug, PartialEq, CultUnion)]
#[cultcache(type_name = "GameCult.Thing.Contract.Node")]
pub enum Node { pub enum Node {
#[cultcache(key = 0)] #[cultcache(key = 0)]
Box(BoxNode), Box(BoxNode),
@ -48,6 +51,8 @@ pub enum Node {
Embed(EmbedNode), Embed(EmbedNode),
#[cultcache(key = 12)] #[cultcache(key = 12)]
Use(UseNode), Use(UseNode),
#[cultcache(key = 13)]
Slot(SlotNode),
} }
#[derive(Clone, Debug, PartialEq, CultSlots)] #[derive(Clone, Debug, PartialEq, CultSlots)]
@ -159,8 +164,10 @@ pub struct TextInputNode {
pub common: NodeCommon, pub common: NodeCommon,
#[cultcache(key = 1)] #[cultcache(key = 1)]
pub multiline: bool, pub multiline: bool,
/// Named `input_kind` in every runtime (Rust `input_kind`, C# `InputKind`, TypeScript `inputKind`): a field
/// named `kind` collides with the union tag in TypeScript. The wire is the slot key, 2.
#[cultcache(key = 2)] #[cultcache(key = 2)]
pub kind: InputKind, pub input_kind: InputKind,
#[cultcache(key = 3)] #[cultcache(key = 3)]
pub placeholder: TextSource, pub placeholder: TextSource,
#[cultcache(key = 4)] #[cultcache(key = 4)]
@ -309,6 +316,13 @@ pub struct CompositionRef {
pub version: Version, pub version: Version,
} }
impl CompositionRef {
/// The record key of the composition this names, from the one key function.
pub fn record_key(&self) -> String {
composition_key(&self.publisher, &self.name, self.version)
}
}
#[derive(Clone, Debug, PartialEq, CultSlots)] #[derive(Clone, Debug, PartialEq, CultSlots)]
pub struct UseNode { pub struct UseNode {
#[cultcache(key = 0)] #[cultcache(key = 0)]
@ -319,6 +333,15 @@ pub struct UseNode {
pub args: Vec<Arg>, pub args: Vec<Arg>,
} }
/// Where a composition body places the nodes passed for its Slot parameter `param`. Only a child
/// list of a composition body holds one, and resolve refuses it elsewhere. It carries no
/// `NodeCommon`: the argument's nodes, keeping their caller-scope ids, replace it.
#[derive(Clone, Debug, PartialEq, CultSlots)]
pub struct SlotNode {
#[cultcache(key = 0)]
pub param: ParamName,
}
#[derive(Clone, Debug, PartialEq, CultSlots)] #[derive(Clone, Debug, PartialEq, CultSlots)]
pub struct Arg { pub struct Arg {
#[cultcache(key = 0)] #[cultcache(key = 0)]
@ -422,7 +445,7 @@ pub struct SurfaceDocument {
pub title: String, pub title: String,
#[cultcache(key = 4)] #[cultcache(key = 4)]
pub root: Node, pub root: Node,
#[cultcache(key = 5)] #[cultcache(key = 5, type_name = "System.Collections.Immutable.ImmutableArray<GameCult.Thing.Contract.CommandDecl>")]
pub commands: Vec<CommandDecl>, pub commands: Vec<CommandDecl>,
} }
@ -442,7 +465,7 @@ pub struct CompositionDocument {
pub name: Segment, pub name: Segment,
#[cultcache(key = 2)] #[cultcache(key = 2)]
pub version: Version, pub version: Version,
#[cultcache(key = 3)] #[cultcache(key = 3, type_name = "System.Collections.Immutable.ImmutableArray<GameCult.Thing.Contract.ParamDecl>")]
pub params: Vec<ParamDecl>, pub params: Vec<ParamDecl>,
#[cultcache(key = 4)] #[cultcache(key = 4)]
pub body: Node, pub body: Node,

View file

@ -41,6 +41,7 @@ pub struct FailedOutcome {
} }
#[derive(Clone, Debug, PartialEq, CultUnion)] #[derive(Clone, Debug, PartialEq, CultUnion)]
#[cultcache(type_name = "GameCult.Thing.Contract.Outcome")]
pub enum Outcome { pub enum Outcome {
#[cultcache(key = 0)] #[cultcache(key = 0)]
Pending(PendingOutcome), Pending(PendingOutcome),

View file

@ -81,7 +81,9 @@ pub enum StateSource {
Item, Item,
} }
/// A state record. An absent provider is the publisher of the document. /// A state record. An absent provider is the publisher of the document. `schema` is the id the
/// provider's record type is registered under in its store: a provider's state type must have its
/// entry type equal to that schema id, because a store names a record's schema by its entry type.
#[derive(Clone, Debug, PartialEq, CultSlots)] #[derive(Clone, Debug, PartialEq, CultSlots)]
pub struct StateRef { pub struct StateRef {
#[cultcache(key = 0)] #[cultcache(key = 0)]

View file

@ -0,0 +1,60 @@
//! The catalog rows the five document kinds publish are the rows the C# package declares:
//! `tests/thing-contract-parity/catalog-members.tsv`, which NameSetTests (C#) and parity.test.ts
//! (TypeScript) are held to as well. Schema ids differ by writer, so the comparison is by group,
//! as `catalogGroups` in parity.test.ts makes it.
use std::path::PathBuf;
use cultcache_rs::{DatabaseEntry, SchemaCatalogMember, SingleFileMessagePackBackingStore};
use thing_contract::*;
fn tsv_groups() -> Vec<String> {
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/thing-contract-parity/catalog-members.tsv");
let text = std::fs::read_to_string(path).unwrap();
let mut groups: Vec<(String, Vec<String>)> = Vec::new();
for row in text.lines().filter(|line| !line.trim().is_empty()) {
let (schema, rest) = row.split_once('\t').unwrap();
match groups.iter_mut().find(|(id, _)| id == schema) {
Some((_, rows)) => rows.push(rest.to_string()),
None => groups.push((schema.to_string(), vec![rest.to_string()])),
}
}
sorted(groups.into_iter().map(|(_, rows)| rows.join("\n")).collect())
}
fn group(members: &[SchemaCatalogMember]) -> String {
members.iter().map(|m| format!("{}\t{}\t{}", m.slot, m.member_name, m.type_name)).collect::<Vec<_>>().join("\n")
}
fn sorted(mut groups: Vec<String>) -> Vec<String> {
groups.sort();
groups
}
#[test]
fn rows_equal_the_csharp_file() {
let mine = sorted(vec![
group(&SurfaceDocument::schema_members()),
group(&CompositionDocument::schema_members()),
group(&CommandInvocation::schema_members()),
group(&CommandResult::schema_members()),
group(&AssetCatalog::schema_members()),
]);
assert_eq!(mine, tsv_groups());
}
#[test]
fn the_written_store_carries_the_rows() {
// goldens.rs writes a store of one record per kind and compares it byte for byte with the
// committed surface.cc, so the committed file's catalog is the catalog the crate writes. It is
// copied first: reading a store creates a lock file beside it.
let committed = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/goldens/surface.cc");
let work = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("catalog-members");
std::fs::create_dir_all(&work).unwrap();
let copy = work.join("surface.cc");
std::fs::copy(committed, &copy).unwrap();
let catalog = SingleFileMessagePackBackingStore::new(&copy).pull_schema_catalog().unwrap();
let from_store = sorted(catalog.iter().map(|entry| group(&entry.members)).collect());
assert_eq!(from_store, tsv_groups());
let _ = std::fs::remove_dir_all(&work);
}

View file

@ -2,42 +2,24 @@
//! byte. The TypeScript and C# packages and core are held to these files; none of them writes //! byte. The TypeScript and C# packages and core are held to these files; none of them writes
//! one. `THING_BLESS=1` rewrites them; any other run compares. //! one. `THING_BLESS=1` rewrites them; any other run compares.
mod common;
use std::collections::BTreeSet; use std::collections::BTreeSet;
use std::fmt::Debug; use std::fmt::Debug;
use std::path::PathBuf; use std::path::PathBuf;
use common::*; use thing_testkit::{build::*, golden, store};
use cultcache_rs::{CultCache, CultCacheEnvelope, CultCacheRegistry, DatabaseEntry, SingleFileMessagePackBackingStore}; use cultcache_rs::{CultCache, CultCacheEnvelope, CultCacheRegistry, DatabaseEntry};
use thing_contract::*; use thing_contract::*;
const PINNED_CLOCK: &str = "2026-01-01T00:00:00Z";
// A value that must never appear in a refusal.
const CANARY: &str = "CANARY-7f3a91c2";
fn goldens_dir() -> PathBuf { fn goldens_dir() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/goldens") PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/goldens")
} }
fn blessing() -> bool { // A value that must never appear in a refusal.
std::env::var("THING_BLESS").as_deref() == Ok("1") const CANARY: &str = "CANARY-7f3a91c2";
}
/// Bless the file or compare against it. Returns the committed bytes.
fn golden_bytes(file: &str, produced: &[u8]) -> Vec<u8> {
let path = goldens_dir().join(file);
if blessing() {
std::fs::write(&path, produced).unwrap_or_else(|error| panic!("{file}: {error}"));
}
let committed = std::fs::read(&path).unwrap_or_else(|error| panic!("{file}: {error}"));
assert_eq!(committed, produced, "{file}: the committed golden differs from what the crate writes");
committed
}
fn golden<T: DatabaseEntry + PartialEq + Debug>(name: &str, value: &T) -> String { fn golden<T: DatabaseEntry + PartialEq + Debug>(name: &str, value: &T) -> String {
let produced = rmp_serde::to_vec(value).unwrap(); let produced = rmp_serde::to_vec(value).unwrap();
let committed = golden_bytes(&format!("{name}.bin"), &produced); let committed = golden::check(&goldens_dir(), &format!("{name}.bin"), &produced);
let decoded: T = rmp_serde::from_slice(&committed).unwrap_or_else(|error| panic!("{name}: {error}")); let decoded: T = rmp_serde::from_slice(&committed).unwrap_or_else(|error| panic!("{name}: {error}"));
assert_eq!(&decoded, value, "{name}: the golden does not decode to the constructed value"); assert_eq!(&decoded, value, "{name}: the golden does not decode to the constructed value");
assert_eq!(rmp_serde::to_vec(&decoded).unwrap(), committed, "{name}: re-encoding changed the bytes"); assert_eq!(rmp_serde::to_vec(&decoded).unwrap(), committed, "{name}: re-encoding changed the bytes");
@ -150,7 +132,7 @@ fn full_surface() -> SurfaceDocument {
Node::TextInput(TextInputNode { Node::TextInput(TextInputNode {
common: common("name-input"), common: common("name-input"),
multiline: true, multiline: true,
kind: InputKind::Number, input_kind: InputKind::Number,
placeholder: lit_text("name"), placeholder: lit_text("name"),
initial: TextSource::Param(param("initial")), initial: TextSource::Param(param("initial")),
submit: command("rename"), submit: command("rename"),
@ -158,7 +140,7 @@ fn full_surface() -> SurfaceDocument {
Node::TextInput(TextInputNode { Node::TextInput(TextInputNode {
common: common("title-input"), common: common("title-input"),
multiline: false, multiline: false,
kind: InputKind::Text, input_kind: InputKind::Text,
placeholder: lit_text("title"), placeholder: lit_text("title"),
initial: TextSource::Param(param("initial")), initial: TextSource::Param(param("initial")),
submit: command("retitle"), submit: command("retitle"),
@ -384,7 +366,10 @@ fn full_composition() -> CompositionDocument {
.into_iter() .into_iter()
.map(|(name, kind)| ParamDecl { name: name.into(), kind }) .map(|(name, kind)| ParamDecl { name: name.into(), kind })
.collect(), .collect(),
body: boxed("panel-root", vec![text("panel-title", "t"), inner_use]), body: boxed(
"panel-root",
vec![text("panel-title", "t"), inner_use, Node::Slot(SlotNode { param: param("body") })],
),
} }
} }
@ -435,26 +420,17 @@ fn asset_catalog() -> AssetCatalog {
/// A store with one record of each kind, written by cultcache-rs under a pinned clock. /// A store with one record of each kind, written by cultcache-rs under a pinned clock.
fn write_store(path: &std::path::Path) { fn write_store(path: &std::path::Path) {
let _ = std::fs::remove_file(path); let mut cache = store::create(path);
let mut cache = CultCache::new();
ThingContract.register_entries(&mut cache).unwrap();
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(path)).unwrap();
let surface = full_surface(); let surface = full_surface();
let composition = full_composition(); let composition = full_composition();
let invocation = invocation(); let invocation = invocation();
let result = CommandResult::pending(&invocation, seq(1), "working"); let result = CommandResult::pending(&invocation, seq(1), "working");
let catalog = asset_catalog(); let catalog = asset_catalog();
put(&mut cache, &surface.record_key(), &surface); store::put_pinned(&mut cache, &surface.record_key(), &surface);
put(&mut cache, &composition.record_key(), &composition); store::put_pinned(&mut cache, &composition.record_key(), &composition);
put(&mut cache, &invocation.record_key(), &invocation); store::put_pinned(&mut cache, &invocation.record_key(), &invocation);
put(&mut cache, &result.record_key(), &result); store::put_pinned(&mut cache, &result.record_key(), &result);
put(&mut cache, &catalog.record_key(), &catalog); store::put_pinned(&mut cache, &catalog.record_key(), &catalog);
}
fn put<T: DatabaseEntry>(cache: &mut CultCache, key: &str, value: &T) {
let (mut envelope, _) = cache.prepare_entry(key, value).unwrap();
envelope.stored_at = PINNED_CLOCK.into();
cache.put_envelope::<T>(envelope).unwrap();
} }
fn envelope<T: DatabaseEntry>(key: &str, payload: Vec<u8>) -> CultCacheEnvelope { fn envelope<T: DatabaseEntry>(key: &str, payload: Vec<u8>) -> CultCacheEnvelope {
@ -462,17 +438,17 @@ fn envelope<T: DatabaseEntry>(key: &str, payload: Vec<u8>) -> CultCacheEnvelope
key: key.into(), key: key.into(),
r#type: T::TYPE.into(), r#type: T::TYPE.into(),
payload, payload,
stored_at: PINNED_CLOCK.into(), stored_at: store::PINNED_CLOCK.into(),
schema_id: Some(T::TYPE.into()), schema_id: Some(T::TYPE.into()),
} }
} }
fn open_store(path: &std::path::Path) -> CultCache { #[test]
let mut cache = CultCache::new(); fn slot_arm_bytes() {
ThingContract.register_entries(&mut cache).unwrap(); let slot = Node::Slot(SlotNode { param: param("body") });
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(path)).unwrap(); let bytes = rmp_serde::to_vec(&slot).unwrap();
cache.pull_all_backing_stores().unwrap(); assert_eq!(bytes, [0x92, 0x0D, 0x91, 0x91, 0xA4, 0x62, 0x6F, 0x64, 0x79]);
cache assert_eq!(rmp_serde::from_slice::<Node>(&bytes).unwrap(), slot);
} }
#[test] #[test]
@ -491,7 +467,7 @@ fn goldens_match() {
// that no case names is an orphan. // that no case names is an orphan.
let refusals = refusal_payloads(); let refusals = refusal_payloads();
for (name, bytes) in &refusals { for (name, bytes) in &refusals {
golden_bytes(&format!("{name}.bin"), bytes); golden::check(&goldens_dir(), &format!("{name}.bin"), bytes);
names.insert((*name).to_string()); names.insert((*name).to_string());
} }
let on_disk: BTreeSet<String> = std::fs::read_dir(goldens_dir()) let on_disk: BTreeSet<String> = std::fs::read_dir(goldens_dir())
@ -504,10 +480,10 @@ fn goldens_match() {
// The store: one record of each kind, written under a pinned clock, byte for byte. // The store: one record of each kind, written under a pinned clock, byte for byte.
let scratch = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("goldens-surface.cc"); let scratch = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("goldens-surface.cc");
write_store(&scratch); write_store(&scratch);
let committed = golden_bytes("surface.cc", &std::fs::read(&scratch).unwrap()); let committed = golden::check(&goldens_dir(), "surface.cc", &std::fs::read(&scratch).unwrap());
let reopened = goldens_dir().join("surface.cc"); let reopened = goldens_dir().join("surface.cc");
assert_eq!(std::fs::read(&reopened).unwrap(), committed); assert_eq!(std::fs::read(&reopened).unwrap(), committed);
let cache = open_store(&scratch); let cache = store::open(&scratch);
let surface = full_surface(); let surface = full_surface();
assert_eq!(cache.get::<SurfaceDocument>(&surface.record_key()).unwrap(), Some(surface)); assert_eq!(cache.get::<SurfaceDocument>(&surface.record_key()).unwrap(), Some(surface));
let composition = full_composition(); let composition = full_composition();
@ -553,10 +529,11 @@ fn refusal_payloads() -> Vec<(&'static str, Vec<u8>)> {
let root = text("root", "x"); let root = text("root", "x");
vec![ vec![
("result-thing1-flat", rmp_serde::to_vec_named(&flat).unwrap()), ("result-thing1-flat", rmp_serde::to_vec_named(&flat).unwrap()),
// A surface whose root is an arm key the Node union does not declare. // A surface whose root is an arm key the Node union does not declare: 14 is the first key
// Node does not declare (Slot is 13).
( (
"node-unknown-arm", "node-unknown-arm",
rmp_serde::to_vec(&("provider.a", "main", 1i64, CANARY, (13i32, (CANARY,)), unit)).unwrap(), rmp_serde::to_vec(&("provider.a", "main", 1i64, CANARY, (14i32, (CANARY,)), unit)).unwrap(),
), ),
// A result whose outcome is an arm key the Outcome union does not declare. // A result whose outcome is an arm key the Outcome union does not declare.
("outcome-unknown-arm", rmp_serde::to_vec(&("inv-1", 1i32, (4i32, (CANARY,)))).unwrap()), ("outcome-unknown-arm", rmp_serde::to_vec(&("inv-1", 1i32, (4i32, (CANARY,)))).unwrap()),
@ -591,7 +568,7 @@ fn refusal_payloads() -> Vec<(&'static str, Vec<u8>)> {
#[test] #[test]
fn refusal_cases() { fn refusal_cases() {
let payloads: std::collections::BTreeMap<_, _> = refusal_payloads().into_iter().collect(); let payloads: std::collections::BTreeMap<_, _> = refusal_payloads().into_iter().collect();
let committed = |name: &str| golden_bytes(&format!("{name}.bin"), &payloads[name]); let committed = |name: &str| golden::check(&goldens_dir(), &format!("{name}.bin"), &payloads[name]);
// Stored under their key, each is refused naming the kind and the key, never a value. // Stored under their key, each is refused naming the kind and the key, never a value.
let cases: [(&str, &str, &str); 7] = [ let cases: [(&str, &str, &str); 7] = [
@ -623,7 +600,7 @@ fn refusal_cases() {
} }
// Decoded directly, the refusal names the union and the arm key, and never the payload. // Decoded directly, the refusal names the union and the arm key, and never the payload.
for (name, union, key) in [("node-unknown-arm", "Node", "13"), ("outcome-unknown-arm", "Outcome", "4")] { for (name, union, key) in [("node-unknown-arm", "Node", "14"), ("outcome-unknown-arm", "Outcome", "4")] {
let bytes = committed(name); let bytes = committed(name);
let message = if union == "Node" { let message = if union == "Node" {
rmp_serde::from_slice::<SurfaceDocument>(&bytes).unwrap_err().to_string() rmp_serde::from_slice::<SurfaceDocument>(&bytes).unwrap_err().to_string()
@ -665,13 +642,6 @@ fn refusal_cases() {
#[test] #[test]
fn deep_tree() { fn deep_tree() {
// Decoding a Node costs tens of KiB of debug stack per nesting level, so the chain runs on a
// thread that has the room; the 2 MiB default does not. The hazard is CultCache's, owned by
// cultlib-gaps:follow_up:decode-stack-safety; the test stays on the big thread until it lands.
std::thread::Builder::new().stack_size(16 * 1024 * 1024).spawn(deep_tree_body).unwrap().join().unwrap();
}
fn deep_tree_body() {
// A 64-deep Box chain. // A 64-deep Box chain.
let mut chain = text("leaf", "bottom"); let mut chain = text("leaf", "bottom");
for depth in (0..64).rev() { for depth in (0..64).rev() {
@ -698,15 +668,12 @@ fn deep_tree_body() {
}; };
let path = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("deep-tree.cc"); let path = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("deep-tree.cc");
let _ = std::fs::remove_file(&path);
{ {
let mut cache = CultCache::new(); let mut cache = store::create(&path);
ThingContract.register_entries(&mut cache).unwrap(); store::put_pinned(&mut cache, &deep.record_key(), &deep);
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&path)).unwrap(); store::put_pinned(&mut cache, &wide.record_key(), &wide);
put(&mut cache, &deep.record_key(), &deep);
put(&mut cache, &wide.record_key(), &wide);
} }
let cache = open_store(&path); let cache = store::open(&path);
assert_eq!(cache.get::<SurfaceDocument>(&deep.record_key()).unwrap(), Some(deep)); assert_eq!(cache.get::<SurfaceDocument>(&deep.record_key()).unwrap(), Some(deep));
assert_eq!(cache.get::<SurfaceDocument>(&wide.record_key()).unwrap(), Some(wide)); assert_eq!(cache.get::<SurfaceDocument>(&wide.record_key()).unwrap(), Some(wide));
} }

View file

@ -12,8 +12,8 @@ when absent. Arm keys are fixed for v1.
| File | Kind | Decodes to | | File | Kind | Decodes to |
|---|---|---| |---|---|---|
| `surface-all-arms.bin` | `gamecult.thing.surface.v1` | One surface with all 13 node arms (Box 0, Text 1, Image 2, Button 3, Toggle 4, Slider 5, TextInput 6 as both input kinds, Text 0 and Number 1, Select 7, Repeat 8, Overlay 9, Plot 10, Embed 11, Use 12), a Box chain four levels deep, every text, number and bool source arm, every Format arm, both state sources, both member steps, every dimension and colour arm, and two declared commands | | `surface-all-arms.bin` | `gamecult.thing.surface.v1` | One surface with 13 of the 14 node arms (Box 0, Text 1, Image 2, Button 3, Toggle 4, Slider 5, TextInput 6 as both input kinds, Text 0 and Number 1, Select 7, Repeat 8, Overlay 9, Plot 10, Embed 11, Use 12; Slot 13 is in `composition-all-params`, a body being where a slot stands), a Box chain four levels deep, every text, number and bool source arm, every Format arm, both state sources, both member steps, every dimension and colour arm, and two declared commands |
| `composition-all-params.bin` | `gamecult.thing.composition.v1` | A composition with one parameter of each of the 7 kinds, whose body uses a composition with one argument of each of the 7 argument arms | | `composition-all-params.bin` | `gamecult.thing.composition.v1` | A composition with one parameter of each of the 7 kinds, whose body uses a composition with one argument of each of the 7 argument arms and places the body slot (Slot 13) last in its root's children |
| `invocation-all-inputs.bin` | `gamecult.thing.command_invocation.v1` | An invocation with a payload record of bin bytes and one captured input of each of the 4 input arms | | `invocation-all-inputs.bin` | `gamecult.thing.command_invocation.v1` | An invocation with a payload record of bin bytes and one captured input of each of the 4 input arms |
| `result-pending.bin` | `gamecult.thing.command_result.v1` | Outcome Pending, seq 1 | | `result-pending.bin` | `gamecult.thing.command_result.v1` | Outcome Pending, seq 1 |
| `result-completed.bin` | same | Outcome Completed with source version 8, drafts cleared, no effect | | `result-completed.bin` | same | Outcome Completed with source version 8, drafts cleared, no effect |
@ -30,7 +30,7 @@ when absent. Arm keys are fixed for v1.
| File | Payload | Expected | | File | Payload | Expected |
|---|---|---| |---|---|---|
| `result-thing1-flat.bin` | a MessagePack map with named members, the shape a Thing 1 provider wrote for a command result | refused when stored as a command result; the error names the kind and the record key and never a value | | `result-thing1-flat.bin` | a MessagePack map with named members, the shape a Thing 1 provider wrote for a command result | refused when stored as a command result; the error names the kind and the record key and never a value |
| `node-unknown-arm.bin` | a surface whose root node has arm key 13, which Node does not declare | refused; the error names the kind and the record key, and decoded directly it names the union Node and the key 13, and never a value | | `node-unknown-arm.bin` | a surface whose root node has arm key 14, which Node does not declare | refused; the error names the kind and the record key, and decoded directly it names the union Node and the key 14, and never a value |
| `outcome-unknown-arm.bin` | a result whose outcome has arm key 4, which Outcome does not declare | refused in the same way, naming the union Outcome and the key 4 | | `outcome-unknown-arm.bin` | a result whose outcome has arm key 4, which Outcome does not declare | refused in the same way, naming the union Outcome and the key 4 |
| `result-extra-slot.bin` | a Pending result with a fourth slot past the last one declared | read: it decodes to the Pending result with seq 1 (CultLib's extra-trailing-slots ruling: read, never written back) | | `result-extra-slot.bin` | a Pending result with a fourth slot past the last one declared | read: it decodes to the Pending result with seq 1 (CultLib's extra-trailing-slots ruling: read, never written back) |
| `result-seq-zero.bin` | a result whose seq slot is 0 | refused; the error names the kind and the record key, decoded directly it names Seq, and never a value | | `result-seq-zero.bin` | a result whose seq slot is 0 | refused; the error names the kind and the record key, decoded directly it names Seq, and never a value |
@ -40,3 +40,9 @@ when absent. Arm keys are fixed for v1.
| `rgba-channel-out-of-range.bin` | the Rgba slot array `[256, 0, 0, 255]` | refused when decoded as an Rgba: a channel is a byte, 0 to 255 | | `rgba-channel-out-of-range.bin` | the Rgba slot array `[256, 0, 0, 255]` | refused when decoded as an Rgba: a channel is a byte, 0 to 255 |
Domain refusals are the contract's rule, which the TypeScript and C# packages mirror: each is held to refuse these files, without the leaf set a Rust `u8` or a checked newtype has. Domain refusals are the contract's rule, which the TypeScript and C# packages mirror: each is held to refuse these files, without the leaf set a Rust `u8` or a checked newtype has.
## The nil vector
`nil-positions.tsv` is written only by `crates/thing-contract/tests/nil_positions.rs` (`THING_BLESS=1`). For every element inside an array, at every depth, of each value golden above except `surface.cc` (the eleven `.bin` files from `surface-all-arms` to `asset-catalog`), the test replaces that element with nil (`0xC0`) and decodes the whole payload with the Rust decode door, `rmp_serde::from_slice` into the golden's kind. A row is `golden`, `path` (dotted array indices from the root, e.g. `3.0.1`), the element's byte `start` and `end` in the golden, and `ACCEPT` or `REFUSE`. An accepted variant re-encodes to the spliced bytes. Maps are not walked.
A slot is required exactly when its Rust type is not optional, so `REFUSE` rows are the required slots and `ACCEPT` rows the optional ones. The Rust decode door decides every row; the TypeScript and C# packages keep no list of required slots and are held to every row.

File diff suppressed because it is too large Load diff

View file

@ -1 +1 @@
–ªprovider.a¤main¯CANARY-7f3a91c2’ ‘¯CANARY-7f3a91c2<63> –ªprovider.a¤main¯CANARY-7f3a91c2’‘¯CANARY-7f3a91c2<63>

View file

@ -0,0 +1,132 @@
//! The nil vector: for every element of every array of every value golden, the golden with that
//! element replaced by nil, and whether the Rust decode door accepts it. A slot is required
//! exactly when its Rust type is not optional, so the rows are the required-slot set; the C# and
//! TypeScript packages hold no list of their own and are held to every row.
//! `THING_BLESS=1` rewrites `goldens/nil-positions.tsv`; any other run compares.
use std::fmt::Debug;
use std::path::PathBuf;
use serde::Serialize;
use serde::de::DeserializeOwned;
use thing_contract::*;
use thing_testkit::golden;
/// One MessagePack value's byte span; `kids` is set for arrays only (maps are never walked).
struct Span {
start: usize,
end: usize,
kids: Option<Vec<Span>>,
}
fn be(bytes: &[u8], at: usize, width: usize) -> usize {
bytes[at..at + width].iter().fold(0, |acc, byte| acc << 8 | *byte as usize)
}
fn collection(bytes: &[u8], start: usize, mut at: usize, count: usize, is_array: bool) -> Span {
let mut kids = Vec::new();
for _ in 0..count {
let kid = item(bytes, at);
at = kid.end;
kids.push(kid);
}
Span { start, end: at, kids: is_array.then_some(kids) }
}
fn item(bytes: &[u8], at: usize) -> Span {
let tag = bytes[at];
let flat = |len: usize| Span { start: at, end: at + len, kids: None };
match tag {
0x00..=0x7f | 0xe0..=0xff | 0xc0 | 0xc2 | 0xc3 => flat(1),
0x80..=0x8f => collection(bytes, at, at + 1, (tag & 0x0f) as usize * 2, false),
0x90..=0x9f => collection(bytes, at, at + 1, (tag & 0x0f) as usize, true),
0xa0..=0xbf => flat(1 + (tag & 0x1f) as usize),
0xc4 | 0xd9 => flat(2 + be(bytes, at + 1, 1)),
0xc5 | 0xda => flat(3 + be(bytes, at + 1, 2)),
0xc6 | 0xdb => flat(5 + be(bytes, at + 1, 4)),
0xca => flat(5),
0xcb => flat(9),
0xcc | 0xd0 => flat(2),
0xcd | 0xd1 => flat(3),
0xce | 0xd2 => flat(5),
0xcf | 0xd3 => flat(9),
0xdc => collection(bytes, at, at + 3, be(bytes, at + 1, 2), true),
0xdd => collection(bytes, at, at + 5, be(bytes, at + 1, 4), true),
0xde => collection(bytes, at, at + 3, be(bytes, at + 1, 2) * 2, false),
0xdf => collection(bytes, at, at + 5, be(bytes, at + 1, 4) * 2, false),
0xd4 => flat(3),
0xd5 => flat(4),
0xd6 => flat(6),
0xd7 => flat(10),
0xd8 => flat(18),
0xc7 => flat(3 + be(bytes, at + 1, 1)),
0xc8 => flat(4 + be(bytes, at + 1, 2)),
0xc9 => flat(6 + be(bytes, at + 1, 4)),
_ => panic!("unsupported tag {tag:#x} at {at}"),
}
}
/// Every element inside an array, at every depth, in walk order, with its dotted index path.
fn elements(span: &Span, prefix: &str, out: &mut Vec<(String, usize, usize)>) {
for (index, kid) in span.kids.iter().flatten().enumerate() {
let path = if prefix.is_empty() { index.to_string() } else { format!("{prefix}.{index}") };
out.push((path.clone(), kid.start, kid.end));
elements(kid, &path, out);
}
}
/// The rows of one golden: nil spliced over each element, decoded as `T`. An accepted variant
/// must re-encode to the spliced bytes.
fn rows<T: DeserializeOwned + Serialize + Debug>(file: &str, out: &mut String) -> (usize, usize) {
let bytes = golden::read(&goldens_dir(), &format!("{file}.bin"));
let mut found = Vec::new();
elements(&item(&bytes, 0), "", &mut found);
let (mut accepted, mut refused) = (0, 0);
for (path, start, end) in found {
let mut spliced = bytes[..start].to_vec();
spliced.push(0xc0);
spliced.extend_from_slice(&bytes[end..]);
let verdict = match rmp_serde::from_slice::<T>(&spliced) {
Ok(value) => {
assert_eq!(rmp_serde::to_vec(&value).unwrap(), spliced, "{file} {path}: an accepted nil must re-encode to the spliced bytes");
accepted += 1;
"ACCEPT"
}
Err(_) => {
refused += 1;
"REFUSE"
}
};
out.push_str(&format!("{file}\t{path}\t{start}\t{end}\t{verdict}\n"));
}
(accepted, refused)
}
#[test]
fn nil_positions_match() {
let mut table = String::new();
let mut totals = Vec::new();
totals.push(("surface-all-arms", rows::<SurfaceDocument>("surface-all-arms", &mut table)));
totals.push(("composition-all-params", rows::<CompositionDocument>("composition-all-params", &mut table)));
totals.push(("invocation-all-inputs", rows::<CommandInvocation>("invocation-all-inputs", &mut table)));
for file in [
"result-pending",
"result-completed",
"result-completed-open-surface",
"result-completed-open-external",
"result-denied",
"result-denied-no-node",
"result-failed",
] {
totals.push((file, rows::<CommandResult>(file, &mut table)));
}
totals.push(("asset-catalog", rows::<AssetCatalog>("asset-catalog", &mut table)));
for (file, (accepted, refused)) in &totals {
println!("NILTOTAL {file} accept={accepted} refuse={refused}");
}
golden::check(&goldens_dir(), "nil-positions.tsv", table.as_bytes());
}
fn goldens_dir() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/goldens")
}

View file

@ -1,6 +1,4 @@
mod common; use thing_testkit::build::*;
use common::*;
use cultcache_rs::{CultCache, CultCacheEnvelope, CultCacheRegistry, DatabaseEntry, decode_payload}; use cultcache_rs::{CultCache, CultCacheEnvelope, CultCacheRegistry, DatabaseEntry, decode_payload};
use serde::Deserialize; use serde::Deserialize;
use serde::de::IntoDeserializer; use serde::de::IntoDeserializer;

View file

@ -0,0 +1,13 @@
[package]
name = "thing-core"
version = "0.1.0"
edition = "2024"
license = "MIT"
publish = false
[dependencies]
thing-contract = { path = "../thing-contract" }
stacker = "0.1.25"
[dev-dependencies]
thing-testkit = { path = "../thing-testkit" }

View file

@ -0,0 +1,45 @@
//! What core says about a document it could not take whole. The code set is closed: a later
//! cut adds its codes as reviewed changes, never as free strings.
use thing_contract::NodeId;
/// Why a document, or one node of it, was not taken as authored.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Code {
/// The port refused the composition's bytes. A refusal is never absence.
DecodeRefused,
/// No composition is published at the named address.
UnresolvedUse,
/// A composition that uses itself through others, or a chain deeper than the limit.
CompositionCycle,
/// An argument, a body or a composition record that does not fit its Use.
CompositionInvalid,
/// A command no surface declaration names.
UndeclaredCommand,
/// Two nodes of the expanded tree share an id.
DuplicateNodeId,
/// A Param or a Slot outside any composition.
UnboundParam,
/// The expanded tree has too many nodes or is deeper than the depth rule.
ExpansionLimit,
/// The input nests deeper than the expander can recurse. A stack bound, not the depth rule: the depth
/// rule is judged on the finished tree and reports ExpansionLimit.
TooDeepToResolve,
}
impl Code {
/// Whether the fault leaves no tree (the whole document is refused) or only a placeholder.
pub fn refuses_document(self) -> bool {
matches!(self, Code::UndeclaredCommand | Code::DuplicateNodeId | Code::UnboundParam | Code::ExpansionLimit | Code::TooDeepToResolve)
}
}
/// One fault. `detail` names the fault and never carries a state value.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Diagnostic {
pub code: Code,
/// The record key of the surface the fault is in.
pub surface: String,
pub node: Option<NodeId>,
pub detail: String,
}

View file

@ -0,0 +1,6 @@
//! Thing's core: a function of documents, state, input and time. It touches the world only
//! through ports; it reads no clock, spawns nothing and awaits nothing.
pub mod diagnostic;
pub mod port;
pub mod resolve;

View file

@ -0,0 +1,144 @@
//! What core may ask of state. The port reads and queues changes; nothing in it writes, and
//! it never awaits: core drains queued changes inside its frame.
pub mod state;
pub use state::StateValue;
use thing_contract::{AssetCatalog, CommandResult, CompositionDocument, ProviderId, RecordKey, SchemaId, SurfaceDocument};
/// One record: the provider that holds it, its schema and its key.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Address {
pub provider: ProviderId,
pub schema: SchemaId,
pub key: RecordKey,
}
/// Every record of one provider and schema whose key starts with `key_prefix`.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Prefix {
pub provider: ProviderId,
pub schema: SchemaId,
pub key_prefix: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Interest {
Record(Address),
Prefix(Prefix),
}
impl Prefix {
pub fn matches(&self, address: &Address) -> bool {
self.provider == address.provider
&& self.schema == address.schema
&& address.key.as_str().starts_with(&self.key_prefix)
}
}
impl Interest {
/// Whether a change at `address` is of interest.
pub fn matches(&self, address: &Address) -> bool {
match self {
Interest::Record(record) => record == address,
Interest::Prefix(prefix) => prefix.matches(address),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct SubscriptionId(pub u64);
/// A record the port carries, decoded: a contract kind, or a provider's state by its schema's
/// member names. `State::schema` is the schema the record is stored under, which is not the
/// one asked for when the key holds a record of another.
#[derive(Clone, Debug, PartialEq)]
pub enum Record {
Surface(SurfaceDocument),
Composition(CompositionDocument),
Result(CommandResult),
Catalog(AssetCatalog),
State { schema: SchemaId, value: StateValue },
}
#[derive(Clone, Debug, PartialEq)]
pub struct Entry {
pub address: Address,
pub record: Record,
}
/// A record the contract refused. `detail` is the decoder's message, which never carries a
/// value.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Refusal {
pub address: Address,
pub kind: SchemaId,
pub detail: String,
}
/// The answer for one address. A refusal is never absence.
#[derive(Clone, Debug, PartialEq)]
pub enum Lookup {
Present(Entry),
Absent,
Refused(Refusal),
}
#[derive(Clone, Debug, PartialEq)]
pub enum Change {
Upsert(Entry),
Delete(Address),
Refused(Refusal),
}
/// Core's view of state. Object safe, and no method writes.
pub trait StatePort {
fn read(&self, address: &Address) -> Lookup;
/// One lookup per record under the prefix, in key order.
fn list(&self, prefix: &Prefix) -> Vec<Lookup>;
fn subscribe(&mut self, interest: Interest) -> SubscriptionId;
fn unsubscribe(&mut self, id: SubscriptionId);
/// Every change since the last drain that some interest matched when it happened, in mutation
/// order (unsubscribing does not recall changes already queued),
/// each once.
fn drain(&mut self) -> Vec<Change>;
}
#[cfg(test)]
mod tests {
use super::*;
fn address(provider: &str, schema: &str, key: &str) -> Address {
Address { provider: ProviderId::new(provider), schema: SchemaId::new(schema), key: RecordKey::new(key) }
}
fn prefix(provider: &str, schema: &str, key_prefix: &str) -> Prefix {
Prefix { provider: ProviderId::new(provider), schema: SchemaId::new(schema), key_prefix: key_prefix.into() }
}
#[test]
fn a_prefix_matches_provider_schema_and_key_prefix_together() {
let under = prefix("p", "s", "row-");
assert!(under.matches(&address("p", "s", "row-1")));
assert!(under.matches(&address("p", "s", "row-")));
assert!(!under.matches(&address("q", "s", "row-1")));
assert!(!under.matches(&address("p", "t", "row-1")));
assert!(!under.matches(&address("p", "s", "col-1")));
assert!(!under.matches(&address("p", "s", "ro")));
}
#[test]
fn a_record_interest_matches_only_its_address() {
let interest = Interest::Record(address("p", "s", "k"));
assert!(interest.matches(&address("p", "s", "k")));
assert!(!interest.matches(&address("p", "s", "k2")));
assert!(!interest.matches(&address("q", "s", "k")));
assert!(Interest::Prefix(prefix("p", "s", "k")).matches(&address("p", "s", "k2")));
assert!(!Interest::Prefix(prefix("p", "s", "k")).matches(&address("p", "s", "j")));
}
}

View file

@ -0,0 +1,26 @@
//! A provider record's value as core sees it. Core holds no bytes and no reader of them: a state
//! port implementation decodes a record with its schema's member names (the `thing-state` crate)
//! and hands core this tree.
/// A provider record's value: closed, ordered and named, with no case folding.
#[derive(Clone, Debug, PartialEq)]
pub enum StateValue {
Nil,
Bool(bool),
Int(i128),
Float(f64),
Text(String),
Bytes(Vec<u8>),
List(Vec<StateValue>),
Record(Vec<(String, StateValue)>),
}
impl StateValue {
/// The member of a `Record` by exact name; `None` for any other shape or a missing name.
pub fn member(&self, name: &str) -> Option<&StateValue> {
match self {
StateValue::Record(members) => members.iter().find(|(member, _)| member == name).map(|(_, value)| value),
_ => None,
}
}
}

View file

@ -0,0 +1,597 @@
//! The substitution: depth first, order preserving. A surface and a composition body go through
//! the same functions; the scope says whether a Param is bound.
//!
//! Expanded ids: inside the expansion of Use `u`, the body root takes `u`'s id and every other
//! body id `b` becomes `u/b`. Arguments are expanded in the caller's scope before the body sees
//! them, so a Slot argument's nodes keep the ids they had in the caller.
use std::collections::{HashMap, HashSet};
use thing_contract::*;
use crate::diagnostic::{Code, Diagnostic};
use crate::port::{Address, Lookup, Record, StatePort};
use super::{Limits, std as thing_std, validate};
/// The deepest input the expander recurses into. This is a stack bound and not the depth rule: the
/// rule (`Limits::max_tree_depth`) is judged by validate on the finished tree, where a slot argument
/// the body never places does not count. It exists because an in-memory tree from a Rust caller can
/// be deeper than any decoded document (CultCache bounds decoded nesting at 256), and recursion
/// over it would overflow the stack. The recursion grows its own stack (`super::grow`), so the bound
/// holds on any thread.
const STACK_BOUND: usize = 1024;
/// A fault the nearest enclosing Use turns into a placeholder (`Invalid`), or one that ends the
/// whole expansion (`Limit`, or `Stack` for input too deep to recurse into).
pub(super) enum Fault {
Invalid(String),
Limit(String),
Stack(String),
}
type Res<T> = Result<T, Fault>;
fn invalid<T>(detail: String) -> Res<T> {
Err(Fault::Invalid(detail))
}
/// The expansion of one composition body: the Use's id and common, and the finished arguments.
struct Scope {
use_id: NodeId,
root_id: NodeId,
use_visible: BoolSource,
use_a11y: Option<TextSource>,
args: HashMap<String, ArgValue>,
}
pub(super) struct Expander<'a> {
port: &'a dyn StatePort,
limits: &'a Limits,
surface: String,
provider: &'a ProviderId,
commands: HashSet<&'a CommandId>,
pub diagnostics: Vec<Diagnostic>,
pub reads: HashSet<Address>,
nodes: usize,
stack: Vec<CompositionRef>,
current: Option<NodeId>,
}
fn arm_name(value: &ArgValue) -> &'static str {
match value {
ArgValue::Text(_) => "Text",
ArgValue::Number(_) => "Number",
ArgValue::Bool(_) => "Bool",
ArgValue::Bind(_) => "Bind",
ArgValue::Collection(_) => "Collection",
ArgValue::Command(_) => "Command",
ArgValue::Slot(_) => "Slot",
}
}
fn kind_name(kind: &ParamKind) -> &'static str {
match kind {
ParamKind::Text => "Text",
ParamKind::Number => "Number",
ParamKind::Bool => "Bool",
ParamKind::Bind => "Bind",
ParamKind::Collection => "Collection",
ParamKind::Command => "Command",
ParamKind::Slot => "Slot",
}
}
fn wrong_kind<T>(name: &ParamName, value: &ArgValue, position: &str) -> Res<T> {
invalid(format!("param '{}' is a {} argument, used as {position}", name.name, arm_name(value)))
}
impl<'a> Expander<'a> {
pub fn new(document: &'a SurfaceDocument, port: &'a dyn StatePort, limits: &'a Limits) -> Self {
Self {
port,
limits,
surface: document.record_key(),
provider: &document.provider_id,
commands: document.commands.iter().map(|declared| &declared.id).collect(),
diagnostics: Vec::new(),
reads: HashSet::new(),
nodes: 0,
stack: Vec::new(),
current: None,
}
}
pub fn diag(&mut self, code: Code, node: Option<NodeId>, detail: impl Into<String>) {
self.diagnostics.push(Diagnostic { code, surface: self.surface.clone(), node, detail: detail.into() });
}
fn unbound(&mut self, what: &str) {
let node = self.current.clone();
self.diag(Code::UnboundParam, node, format!("{what} outside a composition"));
}
/// The surface root: no scope, no Use above it.
pub fn root(&mut self, root: &Node) -> Res<Node> {
self.node(root, None, 1, false)
}
// ---- positions ----------------------------------------------------------------------
fn id(&self, id: &NodeId, scope: Option<&Scope>) -> NodeId {
match scope {
None => id.clone(),
Some(scope) if *id == scope.root_id => scope.use_id.clone(),
Some(scope) => NodeId::new(format!("{}/{}", scope.use_id.as_str(), id.as_str())),
}
}
fn fill(&self, provider: &Option<ProviderId>) -> Option<ProviderId> {
Some(provider.clone().unwrap_or_else(|| self.provider.clone()))
}
fn bind(&self, bind: &Bind) -> Bind {
let source = match &bind.source {
StateSource::Record(state) => StateSource::Record(StateRef {
provider: self.fill(&state.provider),
schema: state.schema.clone(),
key: state.key.clone(),
}),
StateSource::Item => StateSource::Item,
};
Bind { source, member: bind.member.clone(), format: bind.format.clone() }
}
fn arg_of<'s>(name: &ParamName, scope: &'s Scope) -> Res<&'s ArgValue> {
match scope.args.get(&name.name) {
Some(value) => Ok(value),
None => invalid(format!("the body names param '{}', which the composition does not declare", name.name)),
}
}
fn text(&mut self, source: &TextSource, scope: Option<&Scope>) -> Res<TextSource> {
Ok(match (source, scope) {
(TextSource::Literal(_), _) => source.clone(),
(TextSource::Bound(bind), _) => TextSource::Bound(self.bind(bind)),
(TextSource::Param(name), None) => {
self.unbound(&format!("param '{}'", name.name));
source.clone()
}
(TextSource::Param(name), Some(scope)) => match Self::arg_of(name, scope)? {
ArgValue::Text(arg) => TextSource::Literal(TextLiteral { value: arg.value.clone() }),
ArgValue::Bind(bind) => TextSource::Bound(bind.clone()),
other => return wrong_kind(name, other, "text"),
},
})
}
fn number(&mut self, source: &NumberSource, scope: Option<&Scope>) -> Res<NumberSource> {
Ok(match (source, scope) {
(NumberSource::Literal(_), _) => source.clone(),
(NumberSource::Bound(bind), _) => NumberSource::Bound(self.bind(bind)),
(NumberSource::Param(name), None) => {
self.unbound(&format!("param '{}'", name.name));
source.clone()
}
(NumberSource::Param(name), Some(scope)) => match Self::arg_of(name, scope)? {
ArgValue::Number(arg) => NumberSource::Literal(NumberLiteral { value: arg.value }),
ArgValue::Bind(bind) => NumberSource::Bound(bind.clone()),
other => return wrong_kind(name, other, "a number"),
},
})
}
fn boolean(&mut self, source: &BoolSource, scope: Option<&Scope>) -> Res<BoolSource> {
Ok(match (source, scope) {
(BoolSource::Literal(_), _) => source.clone(),
(BoolSource::Bound(bind), _) => BoolSource::Bound(self.bind(bind)),
(BoolSource::Param(name), None) => {
self.unbound(&format!("param '{}'", name.name));
source.clone()
}
(BoolSource::Param(name), Some(scope)) => match Self::arg_of(name, scope)? {
ArgValue::Bool(arg) => BoolSource::Literal(BoolLiteral { value: arg.value }),
ArgValue::Bind(bind) => BoolSource::Bound(bind.clone()),
other => return wrong_kind(name, other, "a bool"),
},
})
}
/// Substitution only: the form an argument takes, before any position judges it.
fn subst_collection(&mut self, source: &CollectionSource, scope: Option<&Scope>) -> Res<CollectionSource> {
Ok(match (source, scope) {
(CollectionSource::Records(records), _) => CollectionSource::Records(RecordsSource {
provider: self.fill(&records.provider),
schema: records.schema.clone(),
key_prefix: records.key_prefix.clone(),
}),
(CollectionSource::Member(bind), _) => CollectionSource::Member(self.bind(bind)),
(CollectionSource::Param(_), None) => source.clone(),
(CollectionSource::Param(name), Some(scope)) => match Self::arg_of(name, scope)? {
ArgValue::Collection(arg) => arg.source.clone(),
other => return wrong_kind(name, other, "a collection"),
},
})
}
fn collection(&mut self, source: &CollectionSource, scope: Option<&Scope>) -> Res<CollectionSource> {
let found = self.subst_collection(source, scope)?;
if let CollectionSource::Param(name) = &found {
self.unbound(&format!("param '{}'", name.name));
}
Ok(found)
}
fn subst_command(&mut self, command: &CommandRef, scope: Option<&Scope>) -> Res<CommandRef> {
Ok(match (command, scope) {
(_, None) => command.clone(),
(CommandRef::Id(id), Some(_)) => {
return invalid(format!(
"the body names command '{}'; a composition takes its commands as params",
id.id.as_str()
));
}
(CommandRef::Param(name), Some(scope)) => match Self::arg_of(name, scope)? {
ArgValue::Command(arg) => arg.command.clone(),
other => return wrong_kind(name, other, "a command"),
},
})
}
/// A command at its final position: declared by the surface, and no Param.
fn command(&mut self, command: &CommandRef, scope: Option<&Scope>) -> Res<CommandRef> {
let found = self.subst_command(command, scope)?;
match &found {
CommandRef::Id(id) if !self.commands.contains(&id.id) => {
let node = self.current.clone();
self.diag(Code::UndeclaredCommand, node, format!("command '{}' is not declared", id.id.as_str()));
}
CommandRef::Param(name) => self.unbound(&format!("param '{}'", name.name)),
CommandRef::Id(_) => {}
}
Ok(found)
}
fn common(&mut self, common: &NodeCommon, scope: Option<&Scope>, root: bool) -> Res<NodeCommon> {
let id = self.id(&common.id, scope);
self.current = Some(id.clone());
match scope {
// A body root is the Use: its id, and its visibility and label unless the body labels it.
Some(scope) if root => {
if common.visible != BoolSource::Literal(BoolLiteral { value: true }) {
return invalid("the body root's visible is not the literal true; visibility is the Use's".into());
}
let a11y_label = match (&scope.use_a11y, &common.a11y_label) {
(Some(label), _) => Some(label.clone()),
(None, Some(label)) => Some(self.text(label, Some(scope))?),
(None, None) => None,
};
Ok(NodeCommon { id, visible: scope.use_visible.clone(), a11y_label })
}
_ => {
let visible = self.boolean(&common.visible, scope)?;
let a11y_label = common.a11y_label.as_ref().map(|label| self.text(label, scope)).transpose()?;
Ok(NodeCommon { id, visible, a11y_label })
}
}
}
// ---- nodes --------------------------------------------------------------------------
fn count(&mut self, added: usize) -> Res<()> {
self.nodes += added;
if self.nodes > self.limits.max_nodes {
return Err(Fault::Limit(format!("the expansion passed {} nodes", self.limits.max_nodes)));
}
Ok(())
}
/// A child list. In a composition body a Slot is replaced by the nodes passed for it.
fn children(&mut self, list: &[Node], scope: Option<&Scope>, depth: usize) -> Res<Vec<Node>> {
let mut out = Vec::with_capacity(list.len());
for node in list {
match (node, scope) {
(Node::Slot(slot), Some(scope)) => match Self::arg_of(&slot.param, scope)? {
ArgValue::Slot(arg) => {
self.count(arg.nodes.iter().map(validate::size).sum())?;
out.extend(arg.nodes.iter().map(clone_deep));
}
other => return wrong_kind(&slot.param, other, "a slot"),
},
_ => out.push(self.node(node, scope, depth, false)?),
}
}
Ok(out)
}
fn node(&mut self, node: &Node, scope: Option<&Scope>, depth: usize, root: bool) -> Res<Node> {
super::grow(|| self.node_at(node, scope, depth, root))
}
fn node_at(&mut self, node: &Node, scope: Option<&Scope>, depth: usize, root: bool) -> Res<Node> {
if depth > STACK_BOUND {
return Err(Fault::Stack(format!("the input nests deeper than {STACK_BOUND} levels")));
}
self.count(1)?;
// Each arm settles its own positions first and its child lists last: a diagnostic names the
// node being expanded, and a child list moves `current` on.
Ok(match node {
Node::Slot(slot) => match scope {
Some(_) => {
return invalid(format!(
"Slot '{}' is not in a child list of the body; a slot stands only in Box.children, \
Button.content or Overlay.children",
slot.param.name
));
}
None => {
self.current = None;
self.unbound(&format!("Slot '{}'", slot.param.name));
node.clone()
}
},
Node::Use(used) => self.expand_use(used, scope, depth, root)?,
Node::Box(b) => {
let common = self.common(&b.common, scope, root)?;
let children = self.children(&b.children, scope, depth + 1)?;
Node::Box(BoxNode { common, style: b.style.clone(), paint: b.paint.clone(), role: b.role.clone(), children })
}
Node::Text(t) => {
let common = self.common(&t.common, scope, root)?;
let content = self.text(&t.content, scope)?;
Node::Text(TextNode { common, content, ..t.clone() })
}
Node::Image(i) => {
let common = self.common(&i.common, scope, root)?;
let alt = self.text(&i.alt, scope)?;
Node::Image(ImageNode { common, alt, ..i.clone() })
}
Node::Button(b) => {
let common = self.common(&b.common, scope, root)?;
let on_activate = self.command(&b.on_activate, scope)?;
let enabled = self.boolean(&b.enabled, scope)?;
let content = self.children(&b.content, scope, depth + 1)?;
Node::Button(ButtonNode { common, content, on_activate, enabled })
}
Node::Toggle(t) => {
let common = self.common(&t.common, scope, root)?;
let checked = self.boolean(&t.checked, scope)?;
let on_change = self.command(&t.on_change, scope)?;
Node::Toggle(ToggleNode { common, checked, on_change })
}
Node::Slider(s) => {
let common = self.common(&s.common, scope, root)?;
let value = self.number(&s.value, scope)?;
let commit = self.command(&s.commit, scope)?;
Node::Slider(SliderNode { common, value, commit, ..s.clone() })
}
Node::TextInput(t) => {
let common = self.common(&t.common, scope, root)?;
let placeholder = self.text(&t.placeholder, scope)?;
let initial = self.text(&t.initial, scope)?;
let submit = self.command(&t.submit, scope)?;
Node::TextInput(TextInputNode { common, placeholder, initial, submit, ..t.clone() })
}
Node::Select(s) => {
let common = self.common(&s.common, scope, root)?;
let options = match &s.options {
OptionList::Literal(_) => s.options.clone(),
OptionList::Bound(bound) => OptionList::Bound(BoundOptions {
collection: self.collection(&bound.collection, scope)?,
value_member: bound.value_member.clone(),
label_member: bound.label_member.clone(),
}),
};
let value = self.bind(&s.value);
let on_change = self.command(&s.on_change, scope)?;
Node::Select(SelectNode { common, options, value, on_change })
}
Node::Repeat(r) => {
let common = self.common(&r.common, scope, root)?;
let collection = self.collection(&r.collection, scope)?;
let template = std::boxed::Box::new(self.node(&r.template, scope, depth + 1, false)?);
Node::Repeat(RepeatNode { common, collection, key_member: r.key_member.clone(), template })
}
Node::Overlay(o) => {
let common = self.common(&o.common, scope, root)?;
let anchor = match &o.anchor {
Anchor::Viewport => Anchor::Viewport,
Anchor::Node(anchor) => Anchor::Node(AnchorNode { node: self.id(&anchor.node, scope) }),
};
let dismiss = self.command(&o.dismiss, scope)?;
let children = self.children(&o.children, scope, depth + 1)?;
Node::Overlay(OverlayNode { common, anchor, modal: o.modal, dismiss, children })
}
Node::Plot(p) => {
let common = self.common(&p.common, scope, root)?;
Node::Plot(PlotNode { common, series: self.bind(&p.series), ..p.clone() })
}
Node::Embed(e) => {
let common = self.common(&e.common, scope, root)?;
Node::Embed(EmbedNode { common, ..e.clone() })
}
})
}
// ---- compositions -------------------------------------------------------------------
fn load(&mut self, reference: &CompositionRef) -> Result<CompositionDocument, (Code, String)> {
let name = format!("{}.{}.v{}", reference.publisher, reference.name.as_str(), reference.version.get());
if reference.publisher == thing_std::PUBLISHER {
return thing_std::lookup(reference.name.as_str(), reference.version)
.ok_or((Code::UnresolvedUse, format!("no compiled-in composition {name}")));
}
let address = Address {
provider: ProviderId::new(reference.publisher.clone()),
schema: SchemaId::new(CompositionDocument::SCHEMA_NAME),
key: RecordKey::new(reference.record_key()),
};
self.reads.insert(address.clone());
match self.port.read(&address) {
Lookup::Present(entry) => match entry.record {
Record::Composition(composition) => Ok(composition),
_ => Err((Code::CompositionInvalid, format!("the record at {name} is not a composition"))),
},
Lookup::Absent => Err((Code::UnresolvedUse, format!("no composition published at {name}"))),
Lookup::Refused(refusal) => Err((Code::DecodeRefused, format!("{name}: {}", refusal.detail))),
}
}
/// The first thing wrong with the composition against its Use, if anything.
fn misfit(reference: &CompositionRef, composition: &CompositionDocument, args: &[Arg]) -> Option<String> {
if composition.publisher != reference.publisher
|| composition.name != reference.name
|| composition.version != reference.version
{
return Some("the composition record's publisher, name or version differs from the Use's reference".into());
}
let mut declared: HashMap<&str, &ParamKind> = HashMap::new();
for param in &composition.params {
if declared.insert(&param.name, &param.kind).is_some() {
return Some(format!("the composition declares param '{}' twice", param.name));
}
}
let mut given: HashSet<&str> = HashSet::new();
for arg in args {
if !given.insert(&arg.name) {
return Some(format!("argument '{}' is given twice", arg.name));
}
match declared.get(arg.name.as_str()) {
None => return Some(format!("argument '{}' names no param of the composition", arg.name)),
Some(kind) if kind_name(kind) != arm_name(&arg.value) => {
return Some(format!(
"argument '{}' is a {} but the param is a {}",
arg.name,
arm_name(&arg.value),
kind_name(kind)
));
}
Some(_) => {}
}
}
composition
.params
.iter()
.find(|param| !given.contains(param.name.as_str()))
.map(|param| format!("param '{}' has no argument", param.name))
}
/// An argument in the caller's scope: the form the body will place.
fn arg(&mut self, value: &ArgValue, scope: Option<&Scope>, depth: usize) -> Res<ArgValue> {
Ok(match value {
ArgValue::Text(_) | ArgValue::Number(_) | ArgValue::Bool(_) => value.clone(),
ArgValue::Bind(bind) => ArgValue::Bind(self.bind(bind)),
ArgValue::Collection(arg) => {
ArgValue::Collection(CollectionArg { source: self.subst_collection(&arg.source, scope)? })
}
ArgValue::Command(arg) => ArgValue::Command(CommandArg { command: self.subst_command(&arg.command, scope)? }),
ArgValue::Slot(arg) => ArgValue::Slot(SlotArg { nodes: self.children(&arg.nodes, scope, depth + 1)? }),
})
}
fn expand_use(&mut self, used: &UseNode, scope: Option<&Scope>, depth: usize, root: bool) -> Res<Node> {
let common = self.common(&used.common, scope, root)?;
let here = common.id.clone();
let reference = &used.composition;
let placeholder = |common: NodeCommon| Node::Use(UseNode { common, composition: reference.clone(), args: vec![] });
let repeats = self.stack.contains(reference);
if repeats || self.stack.len() >= self.limits.max_use_depth {
let why = if repeats { "uses itself" } else { "is nested too deep" };
self.diag(Code::CompositionCycle, Some(here), format!("the composition {why}"));
return Ok(placeholder(common));
}
let composition = match self.load(reference) {
Ok(composition) => composition,
Err((code, detail)) => {
self.diag(code, Some(here), detail);
return Ok(placeholder(common));
}
};
if let Some(detail) = Self::misfit(reference, &composition, &used.args) {
self.diag(Code::CompositionInvalid, Some(here), detail);
return Ok(placeholder(common));
}
let mark = self.diagnostics.len();
let mut args = HashMap::new();
for arg in &used.args {
args.insert(arg.name.clone(), self.arg(&arg.value, scope, depth)?);
}
let inner = Scope {
use_id: here.clone(),
root_id: body_id(&composition.body),
use_visible: common.visible.clone(),
use_a11y: common.a11y_label.clone(),
args,
};
self.stack.push(reference.clone());
let expanded = self.node(&composition.body, Some(&inner), depth, true);
self.stack.pop();
match expanded {
Ok(node) => Ok(node),
Err(Fault::Invalid(detail)) => {
self.diagnostics.truncate(mark);
self.diag(Code::CompositionInvalid, Some(here), detail);
Ok(placeholder(common))
}
Err(limit) => Err(limit),
}
}
}
/// The id of a body root. A Slot has none, and the body fails on it before an id is read.
/// A copy of an expanded subtree that grows its own stack. The derived `Clone` of `Node` costs about
/// 12 KiB of debug stack per level, so a spliced slot argument up to `STACK_BOUND` levels deep would
/// overflow it; each container here recurses through `grow`. An expanded subtree holds no Slot and no
/// Use with arguments, so the four containers are the only nodes that hold nodes.
fn clone_deep(node: &Node) -> Node {
super::grow(|| match node {
Node::Box(b) => Node::Box(BoxNode {
common: b.common.clone(),
style: b.style.clone(),
paint: b.paint.clone(),
role: b.role.clone(),
children: b.children.iter().map(clone_deep).collect(),
}),
Node::Button(b) => Node::Button(ButtonNode {
common: b.common.clone(),
content: b.content.iter().map(clone_deep).collect(),
on_activate: b.on_activate.clone(),
enabled: b.enabled.clone(),
}),
Node::Overlay(o) => Node::Overlay(OverlayNode {
common: o.common.clone(),
anchor: o.anchor.clone(),
modal: o.modal,
dismiss: o.dismiss.clone(),
children: o.children.iter().map(clone_deep).collect(),
}),
Node::Repeat(r) => Node::Repeat(RepeatNode {
common: r.common.clone(),
collection: r.collection.clone(),
key_member: r.key_member.clone(),
template: std::boxed::Box::new(clone_deep(&r.template)),
}),
other => other.clone(),
})
}
fn body_id(node: &Node) -> NodeId {
match node {
Node::Box(n) => n.common.id.clone(),
Node::Text(n) => n.common.id.clone(),
Node::Image(n) => n.common.id.clone(),
Node::Button(n) => n.common.id.clone(),
Node::Toggle(n) => n.common.id.clone(),
Node::Slider(n) => n.common.id.clone(),
Node::TextInput(n) => n.common.id.clone(),
Node::Select(n) => n.common.id.clone(),
Node::Repeat(n) => n.common.id.clone(),
Node::Overlay(n) => n.common.id.clone(),
Node::Plot(n) => n.common.id.clone(),
Node::Embed(n) => n.common.id.clone(),
Node::Use(n) => n.common.id.clone(),
Node::Slot(_) => NodeId::new(""),
}
}

View file

@ -0,0 +1,108 @@
//! Resolve: the pure expansion of a surface document into a tree with no composition left in it.
//! This is the only code that reads Thing Script structure (Use, Param, CommandRef, node ids).
//! It reads compositions through `StatePort::read` and `thing.std` from a compiled-in table,
//! holds no state, subscribes to nothing and never drains.
mod expand;
pub mod std;
mod validate;
use thing_contract::SurfaceDocument;
use crate::diagnostic::{Code, Diagnostic};
use crate::port::{Address, StatePort};
/// Stack left below which recursion moves to a fresh segment, and the segment's size: the values
/// cultcache-rs uses for decode. Every recursion over a tree runs through `grow`, so a tree as deep
/// as `STACK_BOUND` resolves on a default thread.
const RED_ZONE: usize = 512 * 1024;
const SEGMENT: usize = 2 * 1024 * 1024;
/// Runs one recursive step with room for the next, growing the stack when it is nearly spent.
fn grow<R>(step: impl FnOnce() -> R) -> R {
stacker::maybe_grow(RED_ZONE, SEGMENT, step)
}
/// The bounds of one expansion.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Limits {
/// Compositions nested in one another; a Use deeper than this is a placeholder.
pub max_use_depth: usize,
/// The contract's decode bound; a deeper expanded tree is refused.
pub max_tree_depth: usize,
/// Nodes in the expanded tree; more is refused.
pub max_nodes: usize,
}
impl Default for Limits {
fn default() -> Self {
Self { max_use_depth: 32, max_tree_depth: 256, max_nodes: 65_536 }
}
}
/// A surface document expanded: no Param of any kind remains, every command is declared, every
/// state reference names its provider, node ids are unique, and a Use remains only as a
/// placeholder leaf (its arguments emptied) beside a diagnostic. Only `resolve` builds one.
#[derive(Clone, Debug, PartialEq)]
pub struct ResolvedTree {
document: SurfaceDocument,
}
impl ResolvedTree {
pub fn document(&self) -> &SurfaceDocument {
&self.document
}
}
/// What one expansion found. `tree` is `None` when a fault refuses the whole document.
#[derive(Clone, Debug, PartialEq)]
pub struct Resolution {
pub tree: Option<ResolvedTree>,
/// Expansion faults in expansion pre-order, then the finished tree's faults (duplicate ids, depth)
/// in tree pre-order.
pub diagnostics: Vec<Diagnostic>,
/// Every non-std composition address consulted, whether present, absent or refused, once each, ordered
/// by provider, schema and key.
pub reads: Vec<Address>,
}
pub fn resolve(document: &SurfaceDocument, port: &dyn StatePort, limits: &Limits) -> Resolution {
let mut expander = expand::Expander::new(document, port, limits);
let root = match expander.root(&document.root) {
Ok(root) => Some(root),
Err(expand::Fault::Limit(detail)) => {
expander.diag(Code::ExpansionLimit, None, detail);
None
}
Err(expand::Fault::Stack(detail)) => {
expander.diag(Code::TooDeepToResolve, None, detail);
None
}
Err(expand::Fault::Invalid(detail)) => {
expander.diag(Code::CompositionInvalid, None, detail);
None
}
};
let mut diagnostics = ::std::mem::take(&mut expander.diagnostics);
let mut reads: Vec<Address> = ::std::mem::take(&mut expander.reads).into_iter().collect();
reads.sort_by(|a, b| {
let key = |address: &Address| (address.provider.as_str().to_string(), address.schema.as_str().to_string(), address.key.as_str().to_string());
key(a).cmp(&key(b))
});
let tree = root.and_then(|root| {
diagnostics.extend(validate::check(&root, limits, &document.record_key()));
let refused = diagnostics.iter().any(|diagnostic| diagnostic.code.refuses_document());
// Field by field: `..document.clone()` would clone the whole input tree to discard it.
(!refused).then(|| ResolvedTree {
document: SurfaceDocument {
provider_id: document.provider_id.clone(),
label: document.label.clone(),
version: document.version,
title: document.title.clone(),
root,
commands: document.commands.clone(),
},
})
});
Resolution { tree, diagnostics, reads }
}

View file

@ -0,0 +1,95 @@
//! `thing.std`: the compositions compiled into core. The port is never asked for this
//! publisher, so no provider can shadow one.
use thing_contract::*;
/// The publisher whose compositions are compiled in.
pub const PUBLISHER: &str = "thing.std";
/// Every compiled-in composition.
pub fn all() -> Vec<CompositionDocument> {
vec![stat(), card()]
}
pub(super) fn lookup(name: &str, version: Version) -> Option<CompositionDocument> {
all().into_iter().find(|composition| composition.name.as_str() == name && composition.version == version)
}
fn segment(name: &str) -> Segment {
Segment::new(name).expect("a std name is a segment")
}
fn common(id: &str) -> NodeCommon {
NodeCommon { id: NodeId::new(id), visible: BoolSource::Literal(BoolLiteral { value: true }), a11y_label: None }
}
fn text(id: &str, content: TextSource, style_token: &str) -> Node {
Node::Text(TextNode {
common: common(id),
content,
style_token: style_token.into(),
wrap: true,
max_lines: None,
selectable: false,
})
}
fn param(name: &str) -> ParamName {
ParamName { name: name.into() }
}
fn column(id: &str, children: Vec<Node>) -> Node {
let zero = || Dimension::Px(Scalar { value: 0.0 });
let auto = || Dimension::Auto;
let size = |width, height| Size2 { width, height };
let edges = |all: Dimension| Edges { top: all.clone(), right: all.clone(), bottom: all.clone(), left: all };
let style = BoxStyle {
display: Display::Flex,
direction: Direction::Column,
wrap: Wrap::NoWrap,
gap: size(zero(), Dimension::Px(Scalar { value: 4.0 })),
padding: edges(zero()),
margin: edges(zero()),
size: size(auto(), Dimension::Content),
min_size: size(zero(), zero()),
max_size: size(auto(), auto()),
position: Position::Relative,
inset: edges(auto()),
overflow: Overflow::Visible,
align_items: ItemAlign::Stretch,
align_self: ItemAlign::Auto,
align_content: ContentAlign::Start,
justify_content: ContentAlign::Start,
grow: 0.0,
shrink: 1.0,
basis: Dimension::Auto,
grid_columns: vec![],
grid_rows: vec![],
};
let paint = Paint { background: None, border: None, radius: 0.0 };
Node::Box(BoxNode { common: common(id), style, paint, role: Role::Group, children })
}
fn composition(name: &str, params: &[(&str, ParamKind)], body: Node) -> CompositionDocument {
CompositionDocument {
publisher: PUBLISHER.into(),
name: segment(name),
version: Version::new(1).expect("version 1"),
params: params.iter().map(|(name, kind)| ParamDecl { name: (*name).into(), kind: kind.clone() }).collect(),
body,
}
}
/// A label over a bound value.
fn stat() -> CompositionDocument {
let label = text("stat-label", TextSource::Param(param("label")), "caption");
let value = text("stat-value", TextSource::Param(param("value")), "title");
composition("stat", &[("label", ParamKind::Text), ("value", ParamKind::Bind)], column("stat-root", vec![label, value]))
}
/// A title over the nodes passed for `body`.
fn card() -> CompositionDocument {
let title = text("card-title", TextSource::Param(param("title")), "title");
let slot = Node::Slot(SlotNode { param: param("body") });
composition("card", &[("title", ParamKind::Text), ("body", ParamKind::Slot)], column("card-root", vec![title, slot]))
}

View file

@ -0,0 +1,110 @@
//! The one pass over the finished tree: ids unique, and the tree within its depth limit (a slot's
//! nodes are placed deeper than expand saw them). Commands, Params and Slots are judged where they
//! land and the node count is expand's alone (it must stop before it builds a tree it would refuse).
use std::collections::HashSet;
use thing_contract::{Node, NodeId};
use super::Limits;
use crate::diagnostic::{Code, Diagnostic};
/// The child nodes of a node, in order.
fn children(node: &Node) -> &[Node] {
match node {
Node::Box(b) => &b.children,
Node::Button(b) => &b.content,
Node::Overlay(o) => &o.children,
Node::Repeat(r) => std::slice::from_ref(&*r.template),
_ => &[],
}
}
fn id(node: &Node) -> Option<&NodeId> {
match node {
Node::Box(n) => Some(&n.common.id),
Node::Text(n) => Some(&n.common.id),
Node::Image(n) => Some(&n.common.id),
Node::Button(n) => Some(&n.common.id),
Node::Toggle(n) => Some(&n.common.id),
Node::Slider(n) => Some(&n.common.id),
Node::TextInput(n) => Some(&n.common.id),
Node::Select(n) => Some(&n.common.id),
Node::Repeat(n) => Some(&n.common.id),
Node::Overlay(n) => Some(&n.common.id),
Node::Plot(n) => Some(&n.common.id),
Node::Embed(n) => Some(&n.common.id),
Node::Use(n) => Some(&n.common.id),
Node::Slot(_) => None,
}
}
/// Nodes in the subtree, the node itself included.
pub(super) fn size(node: &Node) -> usize {
super::grow(|| 1 + children(node).iter().map(size).sum::<usize>())
}
/// Faults of the finished tree, in pre-order: duplicate ids, then depth. A tree deeper than the limit is not walked further.
pub(super) fn check(root: &Node, limits: &Limits, surface: &str) -> Vec<Diagnostic> {
let mut found = Vec::new();
let fault = |code, node: Option<&NodeId>, detail: String| Diagnostic {
code,
surface: surface.to_string(),
node: node.cloned(),
detail,
};
let mut seen: HashSet<&NodeId> = HashSet::new();
let mut too_deep = false;
let mut stack = vec![(root, 1usize)];
while let Some((node, depth)) = stack.pop() {
if depth > limits.max_tree_depth {
too_deep = true;
continue;
}
if let Some(id) = id(node) {
if !seen.insert(id) {
found.push(fault(Code::DuplicateNodeId, Some(id), format!("node id '{}' occurs twice", id.as_str())));
}
}
stack.extend(children(node).iter().rev().map(|child| (child, depth + 1)));
}
if too_deep {
found.push(fault(Code::ExpansionLimit, None, format!("the tree is deeper than {} levels", limits.max_tree_depth)));
}
found
}
#[cfg(test)]
mod tests {
use thing_testkit::build::{boxed, text};
use super::*;
/// Runs `work` with about `left` bytes of stack remaining: the stack is burned first, so a recursion
/// that does not grow its own runs out inside it.
#[inline(never)]
fn with_stack_left(left: usize, work: &mut dyn FnMut()) {
if stacker::remaining_stack().expect("the thread's stack limit is known") > left {
let burn = [0u8; 4096];
std::hint::black_box(&burn);
with_stack_left(left, work);
std::hint::black_box(&burn);
} else {
work();
}
}
#[test]
fn size_of_a_deep_subtree_grows_its_own_stack() {
// expand counts a slot argument with `size` after the argument was expanded, from wherever the
// stack stands; a 1,000-level argument must not run it out.
let mut deep = text("bottom", "x");
for level in 1..1000 {
deep = boxed(&format!("level-{level}"), vec![deep]);
}
let mut counted = 0;
with_stack_left(100 * 1024, &mut || counted = size(&deep));
assert_eq!(counted, 1000);
// Dropping a tree this deep needs the room the test thread has outside `with_stack_left`.
}
}

View file

@ -0,0 +1,6 @@
# thing-core goldens
`resolve-*.bin` is a CultCache single-file store holding one resolved surface document under the
pinned clock; `resolve-*.txt` is the `{:#?}` text of the same document. The binary is the oracle and
the text is compared beside it. `THING_BLESS=1` through `thing_testkit::golden::check_with_text` is
the only way either changes.

View file

@ -0,0 +1,864 @@
SurfaceDocument {
provider_id: ProviderId(
"provider.stack",
),
label: Segment(
"stack",
),
version: Version(
1,
),
title: "Stack",
root: Box(
BoxNode {
common: NodeCommon {
id: NodeId(
"root",
),
visible: Literal(
BoolLiteral {
value: true,
},
),
a11y_label: None,
},
style: BoxStyle {
display: Flex,
direction: Column,
wrap: NoWrap,
gap: Size2 {
width: Px(
Scalar {
value: 4.0,
},
),
height: Px(
Scalar {
value: 8.0,
},
),
},
padding: Edges {
top: Px(
Scalar {
value: 2.0,
},
),
right: Px(
Scalar {
value: 2.0,
},
),
bottom: Px(
Scalar {
value: 2.0,
},
),
left: Px(
Scalar {
value: 2.0,
},
),
},
margin: Edges {
top: Auto,
right: Auto,
bottom: Auto,
left: Auto,
},
size: Size2 {
width: Percent(
Scalar {
value: 100.0,
},
),
height: Content,
},
min_size: Size2 {
width: Px(
Scalar {
value: 0.0,
},
),
height: Px(
Scalar {
value: 0.0,
},
),
},
max_size: Size2 {
width: Auto,
height: Auto,
},
position: Relative,
inset: Edges {
top: Auto,
right: Auto,
bottom: Auto,
left: Auto,
},
overflow: Visible,
align_items: Stretch,
align_self: Auto,
align_content: Start,
justify_content: SpaceBetween,
grow: 1.0,
shrink: 0.0,
basis: Auto,
grid_columns: [],
grid_rows: [],
},
paint: Paint {
background: None,
border: None,
radius: 0.0,
},
role: Group,
children: [
Box(
BoxNode {
common: NodeCommon {
id: NodeId(
"std-stat",
),
visible: Literal(
BoolLiteral {
value: true,
},
),
a11y_label: None,
},
style: BoxStyle {
display: Flex,
direction: Column,
wrap: NoWrap,
gap: Size2 {
width: Px(
Scalar {
value: 0.0,
},
),
height: Px(
Scalar {
value: 4.0,
},
),
},
padding: Edges {
top: Px(
Scalar {
value: 0.0,
},
),
right: Px(
Scalar {
value: 0.0,
},
),
bottom: Px(
Scalar {
value: 0.0,
},
),
left: Px(
Scalar {
value: 0.0,
},
),
},
margin: Edges {
top: Px(
Scalar {
value: 0.0,
},
),
right: Px(
Scalar {
value: 0.0,
},
),
bottom: Px(
Scalar {
value: 0.0,
},
),
left: Px(
Scalar {
value: 0.0,
},
),
},
size: Size2 {
width: Auto,
height: Content,
},
min_size: Size2 {
width: Px(
Scalar {
value: 0.0,
},
),
height: Px(
Scalar {
value: 0.0,
},
),
},
max_size: Size2 {
width: Auto,
height: Auto,
},
position: Relative,
inset: Edges {
top: Auto,
right: Auto,
bottom: Auto,
left: Auto,
},
overflow: Visible,
align_items: Stretch,
align_self: Auto,
align_content: Start,
justify_content: Start,
grow: 0.0,
shrink: 1.0,
basis: Auto,
grid_columns: [],
grid_rows: [],
},
paint: Paint {
background: None,
border: None,
radius: 0.0,
},
role: Group,
children: [
Text(
TextNode {
common: NodeCommon {
id: NodeId(
"std-stat/stat-label",
),
visible: Literal(
BoolLiteral {
value: true,
},
),
a11y_label: None,
},
content: Literal(
TextLiteral {
value: "Load",
},
),
style_token: "caption",
wrap: true,
max_lines: None,
selectable: false,
},
),
Text(
TextNode {
common: NodeCommon {
id: NodeId(
"std-stat/stat-value",
),
visible: Literal(
BoolLiteral {
value: true,
},
),
a11y_label: None,
},
content: Bound(
Bind {
source: Record(
StateRef {
provider: Some(
ProviderId(
"provider.swarm",
),
),
schema: SchemaId(
"gamecult.thing.test.swarm.v1",
),
key: RecordKey(
"summary",
),
},
),
member: MemberPath {
steps: [
Name(
MemberName {
name: "Load",
},
),
],
},
format: None,
},
),
style_token: "title",
wrap: true,
max_lines: None,
selectable: false,
},
),
],
},
),
Box(
BoxNode {
common: NodeCommon {
id: NodeId(
"outer-card",
),
visible: Literal(
BoolLiteral {
value: true,
},
),
a11y_label: None,
},
style: BoxStyle {
display: Flex,
direction: Column,
wrap: NoWrap,
gap: Size2 {
width: Px(
Scalar {
value: 4.0,
},
),
height: Px(
Scalar {
value: 8.0,
},
),
},
padding: Edges {
top: Px(
Scalar {
value: 2.0,
},
),
right: Px(
Scalar {
value: 2.0,
},
),
bottom: Px(
Scalar {
value: 2.0,
},
),
left: Px(
Scalar {
value: 2.0,
},
),
},
margin: Edges {
top: Auto,
right: Auto,
bottom: Auto,
left: Auto,
},
size: Size2 {
width: Percent(
Scalar {
value: 100.0,
},
),
height: Content,
},
min_size: Size2 {
width: Px(
Scalar {
value: 0.0,
},
),
height: Px(
Scalar {
value: 0.0,
},
),
},
max_size: Size2 {
width: Auto,
height: Auto,
},
position: Relative,
inset: Edges {
top: Auto,
right: Auto,
bottom: Auto,
left: Auto,
},
overflow: Visible,
align_items: Stretch,
align_self: Auto,
align_content: Start,
justify_content: SpaceBetween,
grow: 1.0,
shrink: 0.0,
basis: Auto,
grid_columns: [],
grid_rows: [],
},
paint: Paint {
background: None,
border: None,
radius: 0.0,
},
role: Group,
children: [
Text(
TextNode {
common: NodeCommon {
id: NodeId(
"outer-card/card-title",
),
visible: Literal(
BoolLiteral {
value: true,
},
),
a11y_label: None,
},
content: Literal(
TextLiteral {
value: "Card",
},
),
style_token: "title",
wrap: true,
max_lines: None,
selectable: false,
},
),
Repeat(
RepeatNode {
common: NodeCommon {
id: NodeId(
"outer-card/card-rows",
),
visible: Literal(
BoolLiteral {
value: true,
},
),
a11y_label: None,
},
collection: Records(
RecordsSource {
provider: Some(
ProviderId(
"provider.stack",
),
),
schema: SchemaId(
"gamecult.thing.test.swarm.v1",
),
key_prefix: "mind-",
},
),
key_member: MemberPath {
steps: [
Name(
MemberName {
name: "Id",
},
),
],
},
template: Text(
TextNode {
common: NodeCommon {
id: NodeId(
"outer-card/card-row",
),
visible: Literal(
BoolLiteral {
value: true,
},
),
a11y_label: None,
},
content: Bound(
Bind {
source: Item,
member: MemberPath {
steps: [
Name(
MemberName {
name: "Name",
},
),
],
},
format: None,
},
),
style_token: "body",
wrap: false,
max_lines: None,
selectable: false,
},
),
},
),
Button(
ButtonNode {
common: NodeCommon {
id: NodeId(
"outer-card/card-act",
),
visible: Literal(
BoolLiteral {
value: true,
},
),
a11y_label: None,
},
content: [
Text(
TextNode {
common: NodeCommon {
id: NodeId(
"outer-card/card-act-label",
),
visible: Literal(
BoolLiteral {
value: true,
},
),
a11y_label: None,
},
content: Literal(
TextLiteral {
value: "Open",
},
),
style_token: "body",
wrap: true,
max_lines: None,
selectable: false,
},
),
],
on_activate: Id(
CommandIdRef {
id: CommandId(
"open",
),
},
),
enabled: Literal(
BoolLiteral {
value: true,
},
),
},
),
Box(
BoxNode {
common: NodeCommon {
id: NodeId(
"inner-card",
),
visible: Literal(
BoolLiteral {
value: true,
},
),
a11y_label: None,
},
style: BoxStyle {
display: Flex,
direction: Column,
wrap: NoWrap,
gap: Size2 {
width: Px(
Scalar {
value: 4.0,
},
),
height: Px(
Scalar {
value: 8.0,
},
),
},
padding: Edges {
top: Px(
Scalar {
value: 2.0,
},
),
right: Px(
Scalar {
value: 2.0,
},
),
bottom: Px(
Scalar {
value: 2.0,
},
),
left: Px(
Scalar {
value: 2.0,
},
),
},
margin: Edges {
top: Auto,
right: Auto,
bottom: Auto,
left: Auto,
},
size: Size2 {
width: Percent(
Scalar {
value: 100.0,
},
),
height: Content,
},
min_size: Size2 {
width: Px(
Scalar {
value: 0.0,
},
),
height: Px(
Scalar {
value: 0.0,
},
),
},
max_size: Size2 {
width: Auto,
height: Auto,
},
position: Relative,
inset: Edges {
top: Auto,
right: Auto,
bottom: Auto,
left: Auto,
},
overflow: Visible,
align_items: Stretch,
align_self: Auto,
align_content: Start,
justify_content: SpaceBetween,
grow: 1.0,
shrink: 0.0,
basis: Auto,
grid_columns: [],
grid_rows: [],
},
paint: Paint {
background: None,
border: None,
radius: 0.0,
},
role: Group,
children: [
Text(
TextNode {
common: NodeCommon {
id: NodeId(
"inner-card/card-title",
),
visible: Literal(
BoolLiteral {
value: true,
},
),
a11y_label: None,
},
content: Literal(
TextLiteral {
value: "Card",
},
),
style_token: "title",
wrap: true,
max_lines: None,
selectable: false,
},
),
Repeat(
RepeatNode {
common: NodeCommon {
id: NodeId(
"inner-card/card-rows",
),
visible: Literal(
BoolLiteral {
value: true,
},
),
a11y_label: None,
},
collection: Records(
RecordsSource {
provider: Some(
ProviderId(
"provider.stack",
),
),
schema: SchemaId(
"gamecult.thing.test.swarm.v1",
),
key_prefix: "mind-",
},
),
key_member: MemberPath {
steps: [
Name(
MemberName {
name: "Id",
},
),
],
},
template: Text(
TextNode {
common: NodeCommon {
id: NodeId(
"inner-card/card-row",
),
visible: Literal(
BoolLiteral {
value: true,
},
),
a11y_label: None,
},
content: Bound(
Bind {
source: Item,
member: MemberPath {
steps: [
Name(
MemberName {
name: "Name",
},
),
],
},
format: None,
},
),
style_token: "body",
wrap: false,
max_lines: None,
selectable: false,
},
),
},
),
Button(
ButtonNode {
common: NodeCommon {
id: NodeId(
"inner-card/card-act",
),
visible: Literal(
BoolLiteral {
value: true,
},
),
a11y_label: None,
},
content: [
Text(
TextNode {
common: NodeCommon {
id: NodeId(
"inner-card/card-act-label",
),
visible: Literal(
BoolLiteral {
value: true,
},
),
a11y_label: None,
},
content: Literal(
TextLiteral {
value: "Open",
},
),
style_token: "body",
wrap: true,
max_lines: None,
selectable: false,
},
),
],
on_activate: Id(
CommandIdRef {
id: CommandId(
"open",
),
},
),
enabled: Literal(
BoolLiteral {
value: true,
},
),
},
),
Text(
TextNode {
common: NodeCommon {
id: NodeId(
"inner-note",
),
visible: Literal(
BoolLiteral {
value: true,
},
),
a11y_label: None,
},
content: Literal(
TextLiteral {
value: "nested",
},
),
style_token: "body",
wrap: true,
max_lines: None,
selectable: false,
},
),
],
},
),
],
},
),
],
},
),
commands: [
CommandDecl {
id: CommandId(
"open",
),
payload_schema: SchemaId(
"gamecult.thing.test.open.v1",
),
captures: [],
confirm: None,
},
],
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,12 @@
[package]
name = "thing-state"
version = "0.1.0"
edition = "2024"
license = "MIT"
publish = false
[dependencies]
thing-core = { path = "../thing-core" }
cultcache-rs = { workspace = true }
rmp-serde = { workspace = true }
serde = { workspace = true }

View file

@ -0,0 +1,184 @@
//! The one by-name decode of a provider record. A state port implementation (`MemState` now,
//! thing-mesh next) calls `decode` with the record's payload and the catalog member rows of its
//! schema; core never sees bytes. The catalog names only a document's top-level members, so below
//! that level a payload decodes by its own shape.
//!
//! Registration contract: a provider's state record type must be registered with its entry type
//! equal to its schema id (`TYPE == SCHEMA_NAME`). A CultCache store names a record's schema by
//! its entry type, so the id a `Bind` names is the id the store holds only when the two are one
//! string; the member rows a reader finds are the rows published under that id.
use std::cell::RefCell;
use std::collections::HashSet;
use std::fmt;
use std::io::Cursor;
use cultcache_rs::{SchemaCatalogMember, check_payload_depth};
use thing_core::port::StateValue;
use serde::de::{self, DeserializeSeed, MapAccess, SeqAccess, Visitor};
/// Why a payload is not a `StateValue`. Display names slots, counts and positions, never a value.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum StateDecodeError {
/// The schema published no member rows: a reader cannot name what the writer did not publish.
NoMembers,
NotARecord,
TrailingBytes { count: usize },
TooDeep,
UndescribedSlot { slot: usize },
DuplicateKey { position: usize },
Extension,
Malformed,
}
impl fmt::Display for StateDecodeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NoMembers => f.write_str("the schema published no member rows, so its members cannot be named"),
Self::NotARecord => f.write_str("the payload is not one MessagePack array"),
Self::TrailingBytes { count } => write!(f, "{count} bytes follow the record"),
Self::TooDeep => f.write_str("the payload nests deeper than CultCache admits"),
Self::UndescribedSlot { slot } => write!(f, "slot {slot} holds a value no member row names"),
Self::DuplicateKey { position } => write!(f, "the map repeats a key at entry {position}"),
Self::Extension => f.write_str("the payload holds a MessagePack extension value"),
Self::Malformed => f.write_str("the payload is not well-formed MessagePack"),
}
}
}
impl std::error::Error for StateDecodeError {}
/// Decode `payload`, one MessagePack array, into a `StateValue::Record` of the rows' member
/// names in slot order. A row whose slot lies past the array's end is `Nil`; a non-nil element at
/// a slot no row names is refused. An empty row list is refused.
pub fn decode(payload: &[u8], members: &[SchemaCatalogMember]) -> Result<StateValue, StateDecodeError> {
if members.is_empty() {
return Err(StateDecodeError::NoMembers);
}
check_payload_depth(payload).map_err(|_| StateDecodeError::TooDeep)?;
let failure = RefCell::new(None);
let mut reader = rmp_serde::Deserializer::new(Cursor::new(payload));
let value = match (Shape { failure: &failure }).deserialize(&mut reader) {
Ok(value) => value,
Err(_) => return Err(failure.into_inner().unwrap_or(StateDecodeError::Malformed)),
};
let StateValue::List(elements) = value else { return Err(StateDecodeError::NotARecord) };
let count = payload.len() - reader.position() as usize;
if count != 0 {
return Err(StateDecodeError::TrailingBytes { count });
}
let described: HashSet<usize> = members.iter().map(|row| row.slot as usize).collect();
if let Some(slot) =
elements.iter().enumerate().position(|(slot, value)| !described.contains(&slot) && *value != StateValue::Nil)
{
return Err(StateDecodeError::UndescribedSlot { slot });
}
let mut rows: Vec<&SchemaCatalogMember> = members.iter().collect();
rows.sort_by_key(|row| row.slot);
Ok(StateValue::Record(
rows.into_iter()
.map(|row| (row.member_name.clone(), elements.get(row.slot as usize).cloned().unwrap_or(StateValue::Nil)))
.collect(),
))
}
/// The shape of a payload below the catalog's reach. A semantic refusal is parked in `failure`
/// and surfaces as the serde error that unwinds the walk.
#[derive(Clone, Copy)]
struct Shape<'a> {
failure: &'a RefCell<Option<StateDecodeError>>,
}
impl Shape<'_> {
fn refuse<E: de::Error>(&self, error: StateDecodeError) -> E {
self.failure.borrow_mut().get_or_insert(error);
E::custom("refused")
}
}
impl<'de> DeserializeSeed<'de> for Shape<'_> {
type Value = StateValue;
fn deserialize<D: de::Deserializer<'de>>(self, deserializer: D) -> Result<StateValue, D::Error> {
deserializer.deserialize_any(self)
}
}
impl<'de> Visitor<'de> for Shape<'_> {
type Value = StateValue;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("a MessagePack value")
}
fn visit_unit<E: de::Error>(self) -> Result<StateValue, E> {
Ok(StateValue::Nil)
}
fn visit_none<E: de::Error>(self) -> Result<StateValue, E> {
Ok(StateValue::Nil)
}
fn visit_bool<E: de::Error>(self, value: bool) -> Result<StateValue, E> {
Ok(StateValue::Bool(value))
}
fn visit_i64<E: de::Error>(self, value: i64) -> Result<StateValue, E> {
Ok(StateValue::Int(value.into()))
}
fn visit_u64<E: de::Error>(self, value: u64) -> Result<StateValue, E> {
Ok(StateValue::Int(value.into()))
}
fn visit_f32<E: de::Error>(self, value: f32) -> Result<StateValue, E> {
Ok(StateValue::Float(value.into()))
}
fn visit_f64<E: de::Error>(self, value: f64) -> Result<StateValue, E> {
Ok(StateValue::Float(value))
}
fn visit_str<E: de::Error>(self, value: &str) -> Result<StateValue, E> {
Ok(StateValue::Text(value.into()))
}
fn visit_bytes<E: de::Error>(self, value: &[u8]) -> Result<StateValue, E> {
Ok(StateValue::Bytes(value.into()))
}
fn visit_newtype_struct<D: de::Deserializer<'de>>(self, _: D) -> Result<StateValue, D::Error> {
// rmp-serde presents an extension value as a newtype struct.
Err(self.refuse(StateDecodeError::Extension))
}
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<StateValue, A::Error> {
let mut elements = Vec::new();
while let Some(element) = seq.next_element_seed(self)? {
elements.push(element);
}
Ok(StateValue::List(elements))
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<StateValue, A::Error> {
let mut entries: Vec<(StateValue, StateValue)> = Vec::new();
while let Some(key) = map.next_key_seed(self)? {
let value = map.next_value_seed(self)?;
entries.push((key, value));
}
if entries.iter().all(|(key, _)| matches!(key, StateValue::Text(_))) {
let mut seen = HashSet::new();
let mut members = Vec::with_capacity(entries.len());
for (position, (key, value)) in entries.into_iter().enumerate() {
let StateValue::Text(name) = key else { unreachable!("every key is text") };
if !seen.insert(name.clone()) {
return Err(self.refuse(StateDecodeError::DuplicateKey { position }));
}
members.push((name, value));
}
Ok(StateValue::Record(members))
} else {
Ok(StateValue::List(entries.into_iter().map(|(key, value)| StateValue::List(vec![key, value])).collect()))
}
}
}

View file

@ -0,0 +1,192 @@
//! `thing_state::decode`: each StateValue arm, the slot rules, and the refusals. Payloads are
//! written byte by byte so the test does not lean on the encoder it checks.
use cultcache_rs::SchemaCatalogMember;
use thing_core::port::StateValue::{self, *};
use thing_state::{StateDecodeError, decode};
const CANARY: &str = "CANARY-7f3a91c2";
fn rows(names: &[&str]) -> Vec<SchemaCatalogMember> {
names
.iter()
.enumerate()
.map(|(slot, name)| SchemaCatalogMember {
slot: slot as u32,
member_name: (*name).into(),
type_name: "System.Object".into(),
is_reference: false,
is_many: false,
target_schema_name: None,
is_name: false,
index_alias: None,
})
.collect()
}
fn array(elements: &[Vec<u8>]) -> Vec<u8> {
assert!(elements.len() < 16);
let mut bytes = vec![0x90 | elements.len() as u8];
bytes.extend(elements.iter().flatten());
bytes
}
fn map(pairs: &[(Vec<u8>, Vec<u8>)]) -> Vec<u8> {
let mut bytes = vec![0x80 | pairs.len() as u8];
for (key, value) in pairs {
bytes.extend(key);
bytes.extend(value);
}
bytes
}
fn text(value: &str) -> Vec<u8> {
let mut bytes = vec![0xa0 | value.len() as u8];
bytes.extend(value.as_bytes());
bytes
}
fn int(value: u8) -> Vec<u8> {
assert!(value < 0x80);
vec![value]
}
fn nil() -> Vec<u8> {
vec![0xc0]
}
fn nested(levels: usize) -> Vec<u8> {
let mut bytes = vec![0x91; levels - 1];
bytes.push(0x90);
bytes
}
fn record(pairs: &[(&str, StateValue)]) -> StateValue {
Record(pairs.iter().map(|(name, value)| ((*name).to_string(), value.clone())).collect())
}
#[test]
fn every_arm_decodes_by_the_rows_names() {
let f64_bytes = [vec![0xcb], 2.5f64.to_be_bytes().to_vec()].concat();
let f32_bytes = [vec![0xca], 1.5f32.to_be_bytes().to_vec()].concat();
let u64_max = [vec![0xcf], vec![0xff; 8]].concat();
let i64_min = [vec![0xd3], i64::MIN.to_be_bytes().to_vec()].concat();
let payload = array(&[
nil(),
vec![0xc3],
u64_max,
i64_min,
f64_bytes,
f32_bytes,
text("hi"),
vec![0xc4, 2, 9, 8],
array(&[int(1), int(2)]),
map(&[(text("x"), int(1)), (text("y"), nil())]),
map(&[(int(1), text("one")), (text("k"), int(2))]),
]);
let names = ["Nil", "Bool", "Max", "Min", "F64", "F32", "Text", "Bytes", "List", "Rec", "PairList"];
let decoded = decode(&payload, &rows(&names)).unwrap();
assert_eq!(
decoded,
record(&[
("Nil", Nil),
("Bool", Bool(true)),
("Max", Int(u64::MAX as i128)),
("Min", Int(i64::MIN as i128)),
("F64", Float(2.5)),
("F32", Float(1.5)),
("Text", Text("hi".into())),
("Bytes", Bytes(vec![9, 8])),
("List", List(vec![Int(1), Int(2)])),
("Rec", record(&[("x", Int(1)), ("y", Nil)])),
("PairList", List(vec![List(vec![Int(1), Text("one".into())]), List(vec![Text("k".into()), Int(2)])])),
])
);
assert_eq!(decoded.member("Text"), Some(&Text("hi".into())));
assert_eq!(decoded.member("text"), None, "names match exactly, with no case folding");
}
#[test]
fn a_row_past_the_arrays_end_is_nil() {
let decoded = decode(&array(&[int(7)]), &rows(&["A", "B", "C"])).unwrap();
assert_eq!(decoded, record(&[("A", Int(7)), ("B", Nil), ("C", Nil)]));
}
#[test]
fn rows_decode_in_slot_order_whatever_the_order_given() {
let mut given = rows(&["A", "B"]);
given.reverse();
let decoded = decode(&array(&[int(1), int(2)]), &given).unwrap();
assert_eq!(decoded, record(&[("A", Int(1)), ("B", Int(2))]));
}
#[test]
fn a_non_nil_element_at_an_unnamed_slot_is_refused_and_a_nil_one_is_skipped() {
let mut described = rows(&["A", "B", "C"]);
described.remove(1); // slots 0 and 2
assert_eq!(
decode(&array(&[int(1), int(5), nil()]), &described),
Err(StateDecodeError::UndescribedSlot { slot: 1 })
);
assert_eq!(decode(&array(&[int(1), nil(), int(3)]), &described).unwrap(), record(&[("A", Int(1)), ("C", Int(3))]));
assert_eq!(decode(&array(&[int(1), int(2)]), &rows(&["A"])), Err(StateDecodeError::UndescribedSlot { slot: 1 }));
}
#[test]
fn no_member_rows_refuses_even_a_good_payload() {
assert_eq!(decode(&array(&[int(1)]), &[]), Err(StateDecodeError::NoMembers));
}
#[test]
fn the_payload_must_be_one_array_with_nothing_after_it() {
let names = rows(&["A"]);
assert_eq!(decode(&int(1), &names), Err(StateDecodeError::NotARecord));
assert_eq!(decode(&map(&[(text("A"), int(1))]), &names), Err(StateDecodeError::NotARecord));
let mut trailing = array(&[int(1)]);
trailing.extend([0xc0, 0xc0, 0xc0]);
assert_eq!(decode(&trailing, &names), Err(StateDecodeError::TrailingBytes { count: 3 }));
assert_eq!(decode(&[0x92, 0x01], &names), Err(StateDecodeError::Malformed));
assert_eq!(decode(&[], &names), Err(StateDecodeError::Malformed));
}
#[test]
fn an_extension_value_is_refused_wherever_it_sits() {
let names = rows(&["A"]);
assert_eq!(decode(&array(&[vec![0xd4, 0x01, 0x00]]), &names), Err(StateDecodeError::Extension));
assert_eq!(decode(&array(&[array(&[vec![0xd4, 0x01, 0x00]])]), &names), Err(StateDecodeError::Extension));
}
#[test]
fn a_repeated_text_key_is_refused_by_position() {
let names = rows(&["A"]);
let twice = map(&[(text("a"), int(1)), (text("b"), int(2)), (text("a"), int(3))]);
assert_eq!(decode(&array(&[twice]), &names), Err(StateDecodeError::DuplicateKey { position: 2 }));
// Distinct keys of different kinds are not duplicates.
let mixed = map(&[(int(1), int(1)), (text("1"), int(2))]);
assert!(decode(&array(&[mixed]), &names).is_ok());
}
#[test]
fn nesting_is_bounded_by_cultcaches_depth() {
let names = rows(&["A"]);
assert!(decode(&nested(256), &names).is_ok());
assert_eq!(decode(&nested(257), &names), Err(StateDecodeError::TooDeep));
}
#[test]
fn refusals_never_print_a_value() {
let names = rows(&["A"]);
let secret = text(CANARY);
let cases = [
array(&[secret.clone(), secret.clone()]),
[array(&[secret.clone()]), vec![0xc0]].concat(),
array(&[map(&[(text(CANARY), int(1)), (text(CANARY), int(2))])]),
array(&[secret.clone(), vec![0xd4, 0x01, 0x00]]),
secret.clone(),
];
for payload in cases {
let error = decode(&payload, &names).unwrap_err();
assert!(!error.to_string().contains(CANARY), "{error}");
assert!(!format!("{error:?}").contains(CANARY), "{error:?}");
}
}

View file

@ -0,0 +1,16 @@
[package]
name = "thing-testkit"
version = "0.1.0"
edition = "2024"
license = "MIT"
publish = false
[dependencies]
thing-contract = { path = "../thing-contract" }
cultcache-rs = { workspace = true }
thing-core = { path = "../thing-core" }
thing-state = { path = "../thing-state" }
anyhow = { workspace = true }
rmp-serde = { workspace = true }
serde = { workspace = true }

View file

@ -0,0 +1,34 @@
# thing-testkit fixtures
Each `.cc` is a CultCache single-file store of contract documents, written under the pinned
clock `2026-01-01T00:00:00Z`. The builders are `thing_testkit::fixture`; the bytes below are
frozen, and a normal test run only compares and reads them. The rows are the fixture table of
`docs/thing2-build-spec.md` section 2.5; map rules are those of the build spec.
| File | Holds | Map rules |
|---|---|---|
| `f01-swarm-dashboard.surface.cc` | One surface: a Grid Box root, a Text bound with a Number Format, a Repeat over a RecordsSource prefix whose template binds Item members, and a Button whose CommandRef is declared | 6, 9 |
| `f02-login-effect.surface.cc` | One surface (a Text TextInput and a Button whose command captures it, plus the declared resume command), the CommandInvocation of it, and its two results: Pending, then Completed with an `OpenExternal` effect whose `resume` names the declared command | 1, 2 |
| `f03-input-target.surface.cc` | One surface (an Image over a position: absolute Box with insets, holding a bound label) and the AssetCatalog the Image names | - |
| `f04-form.surface.cc` | One surface (Toggle, Slider, Select with literal options, TextInput of Number kind) and one command capturing all four, its invocation, and a Completed result declaring `clear_drafts` | 1 |
| `f05-modal-overlay.surface.cc` | One surface with a modal Overlay anchored to the viewport, a dismiss CommandRef and two Buttons inside | - |
| `f06-scroll-list.surface.cc` | One surface: a Box with `overflow: scroll` holding a Repeat over a RecordsSource prefix, template keyed by the item's `id` (the 1,000 items are provider state, not here) | - |
| `f07-plot.surface.cc` | One surface with a Plot of each mark (Line, Bar, Area) over a bound series, with and without axis bounds | - |
| `f08-embed-viewport.surface.cc` | One surface: an Embed of declared fixed size as a leaf between two Texts | - |
| `f09-composition-stack.surface.cc` | One surface: a `thing.std` stat Use, and a Use passing one argument of each ArgValue arm whose slot argument holds a second Use (two levels); plus the publisher CompositionDocument both name, whose body places the Slot node | 5 |
| `f10-hostile.surface.cc` | Four surfaces, one hostile shape each: an undeclared CommandRef, a duplicate id after expansion (the surface's `dup-use/shared-id` against the expansion of `dup-use`), an unresolved Use, and a Bind whose schema no fixture provides; plus the one composition (`dup`) the duplicate-id surface expands | 4, 5, 6 |
| `f11-deep.surface.cc` | One surface: the deepest Box chain whose payload CultCache's `check_payload_depth` accepts, found by the builder | - |
| `f11-deep-refused.bin` | The payload of the same chain one Box level deeper, raw: `check_payload_depth` refuses it at depth 257 and so does CultCache. No store can hold it | - |
| `f12-text-edge.surface.cc` | One surface of five Text nodes: bidi (Hebrew and Arabic in Latin), CJK wide characters, combining marks, emoji ZWJ sequences, and a paragraph long enough to wrap | - |
| `state-swarm.state.cc` | Provider state, not contract documents: f01's four swarm records (`summary`, `mind-1`..`mind-3`, schema `gamecult.thing.test.swarm.v1`) written with the test type registered, so the store's catalog publishes the member rows `Id`, `Name`, `Load` | - |
| `state-swarm-members-empty.state.cc` | The same four records written through a hand-implemented twin of the type, whose catalog publishes `[]`: every read of it is refused | - |
A payload the contract refuses cannot live in a store: f11's refused payload is a raw file here, and an
unknown union arm is `crates/thing-contract/tests/goldens/node-unknown-arm.bin`, read in place and fed to
`MemState::put_raw`.
## Regenerate
`THING_BLESS=1 cargo test -p thing-testkit --test fixtures every_fixture_round_trips` rewrites
the files (the two state stores: `--test state the_committed_stores`) through `golden::check`, the one bless door; review the diff before committing. Run
the tests without `THING_BLESS` to compare.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -0,0 +1,3 @@
“²cultcache.store.v1‘—¼gamecult.thing.test.swarm.v1¼gamecult.thing.test.swarm.v1¿gamecult.thing.test.swarm.v1.v1¼gamecult.thing.test.swarm.v1Ùl{"schemaName":"gamecult.thing.test.swarm.v1","schemaVersion":"gamecult.thing.test.swarm.v1.v1","members":[]}‘¼gamecult.thing.test.swarm.v1<EFBFBD>””¦mind-1¼gamecult.thing.test.swarm.v1´2026-01-01T00:00:00ZÄ“¦mind-1¦EurekaË?Ó×
=p£×”¦mind-2¼gamecult.thing.test.swarm.v1´2026-01-01T00:00:00ZÄ“¦mind-2¥LibbyË?â=p£×
=”¦mind-3¼gamecult.thing.test.swarm.v1´2026-01-01T00:00:00ZÄ“¦mind-3¤KikoË?´záG®{”§summary¼gamecult.thing.test.swarm.v1´2026-01-01T00:00:00ZÄ“§summary¥SwarmË?ÚáG®zá

Binary file not shown.

View file

@ -1,7 +1,5 @@
//! Constructors for the values the goldens and the other tests share. Every value is built //! Constructors for the values the contract goldens, the fixtures and the other tests share.
//! through the crate's public types; no bytes are spelled here. //! Every value is built through the crate's public types; no bytes are spelled here.
#![allow(dead_code)]
use thing_contract::*; use thing_contract::*;

View file

@ -0,0 +1,813 @@
//! The frozen fixture stores: typed contract documents built here, encoded through CultCache
//! under a pinned clock, committed under `fixtures/`, and loaded back through the same door
//! every consumer uses. The bless switch is read in `golden::check` alone.
use std::path::PathBuf;
use cultcache_rs::{CultCache, check_payload_depth};
use thing_contract::*;
use crate::build::*;
use crate::{golden, store};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Fixture {
F01SwarmDashboard,
F02LoginEffect,
F03InputTarget,
F04Form,
F05ModalOverlay,
F06ScrollList,
F07Plot,
F08EmbedViewport,
F09CompositionStack,
F10Hostile,
F11Deep,
F12TextEdge,
}
/// The documents of one fixture, each kind in record-key order.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct FixtureSet {
pub surfaces: Vec<SurfaceDocument>,
pub compositions: Vec<CompositionDocument>,
pub catalogs: Vec<AssetCatalog>,
pub invocations: Vec<CommandInvocation>,
pub results: Vec<CommandResult>,
}
impl FixtureSet {
fn sorted(mut self) -> Self {
self.surfaces.sort_by_key(SurfaceDocument::record_key);
self.compositions.sort_by_key(CompositionDocument::record_key);
self.catalogs.sort_by_key(AssetCatalog::record_key);
self.invocations.sort_by_key(CommandInvocation::record_key);
self.results.sort_by_key(CommandResult::record_key);
self
}
fn surfaces(surfaces: Vec<SurfaceDocument>) -> Self {
Self { surfaces, ..Self::default() }.sorted()
}
/// Every document in the set, counted.
pub fn document_count(&self) -> usize {
self.surfaces.len() + self.compositions.len() + self.catalogs.len() + self.invocations.len() + self.results.len()
}
}
impl Fixture {
pub const ALL: [Fixture; 12] = [
Fixture::F01SwarmDashboard,
Fixture::F02LoginEffect,
Fixture::F03InputTarget,
Fixture::F04Form,
Fixture::F05ModalOverlay,
Fixture::F06ScrollList,
Fixture::F07Plot,
Fixture::F08EmbedViewport,
Fixture::F09CompositionStack,
Fixture::F10Hostile,
Fixture::F11Deep,
Fixture::F12TextEdge,
];
pub fn file_name(self) -> &'static str {
match self {
Fixture::F01SwarmDashboard => "f01-swarm-dashboard.surface.cc",
Fixture::F02LoginEffect => "f02-login-effect.surface.cc",
Fixture::F03InputTarget => "f03-input-target.surface.cc",
Fixture::F04Form => "f04-form.surface.cc",
Fixture::F05ModalOverlay => "f05-modal-overlay.surface.cc",
Fixture::F06ScrollList => "f06-scroll-list.surface.cc",
Fixture::F07Plot => "f07-plot.surface.cc",
Fixture::F08EmbedViewport => "f08-embed-viewport.surface.cc",
Fixture::F09CompositionStack => "f09-composition-stack.surface.cc",
Fixture::F10Hostile => "f10-hostile.surface.cc",
Fixture::F11Deep => "f11-deep.surface.cc",
Fixture::F12TextEdge => "f12-text-edge.surface.cc",
}
}
pub fn dir() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("fixtures")
}
/// The documents the builders produce.
pub fn build(self) -> FixtureSet {
match self {
Fixture::F01SwarmDashboard => FixtureSet::surfaces(vec![swarm_dashboard()]),
Fixture::F02LoginEffect => login_effect(),
Fixture::F03InputTarget => input_target(),
Fixture::F04Form => form(),
Fixture::F05ModalOverlay => FixtureSet::surfaces(vec![modal_overlay()]),
Fixture::F06ScrollList => FixtureSet::surfaces(vec![scroll_list()]),
Fixture::F07Plot => FixtureSet::surfaces(vec![plot()]),
Fixture::F08EmbedViewport => FixtureSet::surfaces(vec![embed_viewport()]),
Fixture::F09CompositionStack => {
FixtureSet { surfaces: vec![composition_stack()], compositions: vec![stack_card()], ..FixtureSet::default() }
.sorted()
}
Fixture::F10Hostile => {
FixtureSet { surfaces: hostile(), compositions: vec![hostile_dup()], ..FixtureSet::default() }.sorted()
}
Fixture::F11Deep => FixtureSet::surfaces(vec![deep_surface(deepest_accepted())]),
Fixture::F12TextEdge => FixtureSet::surfaces(vec![text_edge()]),
}
}
/// The file holding the payload one Box level deeper than f11, which the contract refuses.
pub const DEEP_REFUSED: &'static str = "f11-deep-refused.bin";
/// The payload of f11's surface with one more Box level than the bound admits: raw bytes,
/// since no store can hold them.
pub fn deep_refused_payload() -> Vec<u8> {
rmp_serde::to_vec(&deep_surface(deepest_accepted() + 1)).unwrap()
}
/// Bless or compare the committed file of the refused payload; returns the committed bytes.
pub fn write_deep_refused() -> Vec<u8> {
golden::check(&Self::dir(), Self::DEEP_REFUSED, &Self::deep_refused_payload())
}
/// Encode the built documents into a store and bless or compare the committed file; returns
/// the committed bytes.
pub fn write(self) -> Vec<u8> {
let set = self.build();
let bytes = store::bytes(|cache| {
for surface in &set.surfaces {
store::put_pinned(cache, &surface.record_key(), surface);
}
for composition in &set.compositions {
store::put_pinned(cache, &composition.record_key(), composition);
}
for catalog in &set.catalogs {
store::put_pinned(cache, &catalog.record_key(), catalog);
}
for invocation in &set.invocations {
store::put_pinned(cache, &invocation.record_key(), invocation);
}
for result in &set.results {
store::put_pinned(cache, &result.record_key(), result);
}
});
golden::check(&Self::dir(), self.file_name(), &bytes)
}
/// The committed store, opened through the contract. Opening creates a lock file beside the
/// store, so this opens a copy in a directory of its own, removed once the store is read:
/// the fixtures directory is never written.
pub fn open(self) -> CultCache {
let work = store::scratch_dir("open");
let copy = work.join(self.file_name());
std::fs::copy(Self::dir().join(self.file_name()), &copy).unwrap();
let cache = store::open(&copy);
let _ = std::fs::remove_dir_all(&work);
cache
}
/// The committed store, decoded through the contract.
pub fn load(self) -> FixtureSet {
let cache = self.open();
FixtureSet {
surfaces: cache.get_all().unwrap(),
compositions: cache.get_all().unwrap(),
catalogs: cache.get_all().unwrap(),
invocations: cache.get_all().unwrap(),
results: cache.get_all().unwrap(),
}
.sorted()
}
}
const SWARM: &str = "provider.swarm";
const SWARM_SCHEMA: &str = "gamecult.thing.test.swarm.v1";
fn swarm_ref(key: &str) -> StateSource {
StateSource::Record(StateRef {
provider: Some(ProviderId::new(SWARM)),
schema: SchemaId::new(SWARM_SCHEMA),
key: RecordKey::new(key),
})
}
fn swarm_dashboard() -> SurfaceDocument {
let load = Bind {
source: swarm_ref("summary"),
member: path(&["Load"]),
format: Some(Format::Number(NumberFormat { precision: count(1), percent: true, unit: None })),
};
let load_text = Node::Text(TextNode {
common: common("load"),
content: TextSource::Bound(load),
style_token: "title".into(),
wrap: false,
max_lines: Some(count(1)),
selectable: false,
});
let minds = Node::Repeat(RepeatNode {
common: common("minds"),
collection: CollectionSource::Records(RecordsSource {
provider: Some(ProviderId::new(SWARM)),
schema: SchemaId::new(SWARM_SCHEMA),
key_prefix: "mind-".into(),
}),
key_member: path(&["Id"]),
template: std::boxed::Box::new(Node::Text(TextNode {
common: common("mind-name"),
content: TextSource::Bound(item_bind(path(&["Name"]))),
style_token: "body".into(),
wrap: false,
max_lines: Some(count(1)),
selectable: true,
})),
});
let restart = Node::Button(ButtonNode {
common: common("restart"),
content: vec![text("restart-label", "Restart")],
on_activate: command("restart"),
enabled: lit_bool(true),
});
let mut grid = style();
grid.display = Display::Grid;
grid.grid_columns = vec![Dimension::Percent(Scalar { value: 50.0 }), Dimension::Percent(Scalar { value: 50.0 })];
grid.grid_rows = vec![Dimension::Auto, Dimension::Auto];
let root = Node::Box(BoxNode {
common: common("root"),
style: grid,
paint: plain_paint(),
role: Role::Group,
children: vec![load_text, minds, restart],
});
SurfaceDocument {
provider_id: ProviderId::new(SWARM),
label: seg("dashboard"),
version: ver(1),
title: "Swarm".into(),
root,
commands: vec![CommandDecl {
id: CommandId::new("restart"),
payload_schema: SchemaId::new("gamecult.thing.test.restart.v1"),
captures: vec![],
confirm: Some("Restart the swarm?".into()),
}],
}
}
const STACK: &str = "provider.stack";
/// A Use of the publisher's card with one argument of each arm and the given slot children.
fn card_use(id: &str, slot: Vec<Node>) -> Node {
let source = Bind { source: swarm_ref("summary"), member: path(&["Load"]), format: None };
let rows = CollectionSource::Records(RecordsSource {
provider: None,
schema: SchemaId::new(SWARM_SCHEMA),
key_prefix: "mind-".into(),
});
let args = vec![
Arg { name: "title".into(), value: ArgValue::Text(TextArg { value: "Card".into() }) },
Arg { name: "count".into(), value: ArgValue::Number(NumberArg { value: 3.0 }) },
Arg { name: "on".into(), value: ArgValue::Bool(BoolArg { value: true }) },
Arg { name: "source".into(), value: ArgValue::Bind(source) },
Arg { name: "rows".into(), value: ArgValue::Collection(CollectionArg { source: rows }) },
Arg { name: "act".into(), value: ArgValue::Command(CommandArg { command: command("open") }) },
Arg { name: "body".into(), value: ArgValue::Slot(SlotArg { nodes: slot }) },
];
Node::Use(UseNode {
common: common(id),
composition: CompositionRef { publisher: STACK.into(), name: seg("card"), version: ver(1) },
args,
})
}
fn composition_stack() -> SurfaceDocument {
// Two levels: the outer card's slot holds a second card.
let inner = card_use("inner-card", vec![text("inner-note", "nested")]);
let outer = card_use("outer-card", vec![inner]);
// A compiled-in composition: thing.std is never asked of the port.
let std_stat = Node::Use(UseNode {
common: common("std-stat"),
composition: CompositionRef { publisher: "thing.std".into(), name: seg("stat"), version: ver(1) },
args: vec![
Arg { name: "label".into(), value: ArgValue::Text(TextArg { value: "Load".into() }) },
Arg {
name: "value".into(),
value: ArgValue::Bind(Bind { source: swarm_ref("summary"), member: path(&["Load"]), format: None }),
},
],
});
SurfaceDocument {
provider_id: ProviderId::new(STACK),
label: seg("stack"),
version: ver(1),
title: "Stack".into(),
root: boxed("root", vec![std_stat, outer]),
commands: vec![CommandDecl {
id: CommandId::new("open"),
payload_schema: SchemaId::new("gamecult.thing.test.open.v1"),
captures: vec![],
confirm: None,
}],
}
}
fn stack_card() -> CompositionDocument {
let title = Node::Text(TextNode {
common: common("card-title"),
content: TextSource::Param(param("title")),
style_token: "title".into(),
wrap: true,
max_lines: None,
selectable: false,
});
let rows = Node::Repeat(RepeatNode {
common: common("card-rows"),
collection: CollectionSource::Param(param("rows")),
key_member: path(&["Id"]),
template: std::boxed::Box::new(Node::Text(TextNode {
common: common("card-row"),
content: TextSource::Bound(item_bind(path(&["Name"]))),
style_token: "body".into(),
wrap: false,
max_lines: None,
selectable: false,
})),
});
let act = Node::Button(ButtonNode {
common: common("card-act"),
content: vec![text("card-act-label", "Open")],
on_activate: CommandRef::Param(param("act")),
enabled: BoolSource::Param(param("on")),
});
CompositionDocument {
publisher: STACK.into(),
name: seg("card"),
version: ver(1),
params: [
("title", ParamKind::Text),
("count", ParamKind::Number),
("on", ParamKind::Bool),
("source", ParamKind::Bind),
("rows", ParamKind::Collection),
("act", ParamKind::Command),
("body", ParamKind::Slot),
]
.into_iter()
.map(|(name, kind)| ParamDecl { name: name.into(), kind })
.collect(),
body: boxed("card-root", vec![title, rows, act, Node::Slot(SlotNode { param: param("body") })]),
}
}
const HOSTILE: &str = "provider.hostile";
fn hostile_use(id: &str, name: &str) -> Node {
Node::Use(UseNode {
common: common(id),
composition: CompositionRef { publisher: HOSTILE.into(), name: seg(name), version: ver(1) },
args: vec![],
})
}
fn hostile_surface(label: &str, children: Vec<Node>) -> SurfaceDocument {
SurfaceDocument {
provider_id: ProviderId::new(HOSTILE),
label: seg(label),
version: ver(1),
title: label.into(),
root: boxed("root", children),
commands: vec![],
}
}
/// Four surfaces the resolver must refuse or flag, one hostile shape each. A surface whose
/// bytes the contract itself refuses (an unknown union arm) cannot live in a store, so that
/// case is the committed `node-unknown-arm.bin` golden, fed to a fake by the test.
fn hostile() -> Vec<SurfaceDocument> {
let undeclared = Node::Button(ButtonNode {
common: common("go"),
content: vec![text("go-label", "Go")],
on_activate: command("missing"),
enabled: lit_bool(true),
});
let mismatched = Node::Text(TextNode {
common: common("mismatch"),
content: TextSource::Bound(Bind {
source: StateSource::Record(StateRef {
provider: Some(ProviderId::new(HOSTILE)),
schema: SchemaId::new("gamecult.thing.test.nowhere.v1"),
key: RecordKey::new("row-1"),
}),
member: path(&["Name"]),
format: None,
}),
style_token: "body".into(),
wrap: false,
max_lines: None,
selectable: false,
});
vec![
hostile_surface("undeclared-command", vec![undeclared]),
// The composition `dup` emits `shared-id`, which expands to `dup-use/shared-id`; the surface
// authors that same id beside the Use.
hostile_surface("duplicate-id", vec![hostile_use("dup-use", "dup"), text("dup-use/shared-id", "also here")]),
// No composition `ghost` exists anywhere.
hostile_surface("unresolved-use", vec![hostile_use("ghost-use", "ghost")]),
hostile_surface("schema-mismatch", vec![mismatched]),
]
}
/// The one composition a hostile surface needs: the duplicate-id case cannot expand without it.
fn hostile_dup() -> CompositionDocument {
CompositionDocument {
publisher: HOSTILE.into(),
name: seg("dup"),
version: ver(1),
params: vec![],
body: boxed("dup-root", vec![text("shared-id", "from the composition")]),
}
}
// The nine fixtures below bind to test schemas only; the state scripts that fill them belong to
// the bind cut, so no provider state record lives in a fixture.
const TEST_SCHEMA_ROOT: &str = "gamecult.thing.test";
fn decl(id: &str, captures: &[&str], confirm: Option<&str>) -> CommandDecl {
CommandDecl {
id: CommandId::new(id),
payload_schema: SchemaId::new(format!("{TEST_SCHEMA_ROOT}.{id}.v1")),
captures: captures.iter().map(|node| nid(node)).collect(),
confirm: confirm.map(Into::into),
}
}
fn record_member(provider: &str, schema: &str, key: &str, member: &[&str]) -> Bind {
Bind {
source: StateSource::Record(StateRef {
provider: Some(ProviderId::new(provider)),
schema: SchemaId::new(format!("{TEST_SCHEMA_ROOT}.{schema}.v1")),
key: RecordKey::new(key),
}),
member: path(member),
format: None,
}
}
fn surface(provider: &str, label: &str, root: Node, commands: Vec<CommandDecl>) -> SurfaceDocument {
SurfaceDocument {
provider_id: ProviderId::new(provider),
label: seg(label),
version: ver(1),
title: label.into(),
root,
commands,
}
}
/// An invocation of `command` on `surface`, issued at the pinned clock.
fn invoke(surface: &SurfaceDocument, id: &str, command: &str, captured: Vec<CapturedInput>) -> CommandInvocation {
CommandInvocation {
invocation_id: id.into(),
surface_key: surface.record_key(),
surface_version: surface.version.clone(),
command: CommandId::new(command),
payload: RecordPayload {
schema: SchemaId::new(format!("{TEST_SCHEMA_ROOT}.{command}.v1")),
// An empty MessagePack array: the payload record has no slots to fill.
bytes: vec![0x90],
},
captured,
client: "renderer.web".into(),
issued_at: store::PINNED_CLOCK.into(),
delegation: None,
}
}
fn captured(node: &str, value: InputValue) -> CapturedInput {
CapturedInput { node: nid(node), value }
}
fn text_input(id: &str, kind: InputKind, initial: &str, submit: CommandRef) -> Node {
Node::TextInput(TextInputNode {
common: common(id),
multiline: false,
input_kind: kind,
placeholder: lit_text(id),
initial: lit_text(initial),
submit,
})
}
fn button(id: &str, label: &str, on_activate: CommandRef) -> Node {
Node::Button(ButtonNode {
common: common(id),
content: vec![text(&format!("{id}-label"), label)],
on_activate,
enabled: lit_bool(true),
})
}
fn login_effect() -> FixtureSet {
let root = boxed(
"root",
vec![
text_input("username", InputKind::Text, "", command("sign-in")),
button("sign-in-button", "Sign in", command("sign-in")),
],
);
let login = surface(
"provider.login",
"login",
root,
vec![decl("sign-in", &["username"], None), decl("login-resume", &[], None)],
);
let invocation = invoke(
&login,
"6d1c0f52-7a0e-4b53-8f3d-2a9e4c7b1d10",
"sign-in",
vec![captured("username", InputValue::Text(TextValue { value: "ada".into() }))],
);
// The answer arrives in two steps: Pending, then Completed, whose effect sends the user to
// an external page and names the command that runs when they return.
let results = vec![
CommandResult::pending(&invocation, seq(1), "waiting for the identity provider"),
CommandResult::completed(
&invocation,
seq(2),
None,
false,
Some(Effect::OpenExternal(OpenExternalEffect {
url: "https://login.example.test/authorize".into(),
resume: command("login-resume"),
})),
),
];
FixtureSet { surfaces: vec![login], invocations: vec![invocation], results, ..FixtureSet::default() }.sorted()
}
fn input_target() -> FixtureSet {
let provider = "provider.muninn";
let board = Node::Image(ImageNode {
common: common("board"),
catalog: "targets".into(),
asset: "board".into(),
fit: ImageFit::Contain,
alt: lit_text("The board the target sits on"),
});
let label = Node::Text(TextNode {
common: common("target-label"),
content: TextSource::Bound(record_member(provider, "target", "cursor", &["Label"])),
style_token: "body".into(),
wrap: false,
max_lines: Some(count(1)),
selectable: false,
});
// An absolute Box over the Image: insets from the root's top and left edges, a fixed size.
let mut over = style();
over.position = Position::Absolute;
over.inset = Edges { top: px(120.0), right: Dimension::Auto, bottom: Dimension::Auto, left: px(200.0) };
over.size = size2(px(48.0), px(48.0));
let target = Node::Box(BoxNode {
common: common("target"),
style: over,
paint: plain_paint(),
role: Role::Group,
children: vec![label],
});
let mut frame = style();
frame.size = size2(px(640.0), px(360.0));
let root = Node::Box(BoxNode {
common: common("root"),
style: frame,
paint: plain_paint(),
role: Role::Group,
children: vec![board, target],
});
let catalog = AssetCatalog {
provider_id: ProviderId::new(provider),
catalog_id: seg("targets"),
version: ver(1),
assets: vec![AssetEntry {
id: "board".into(),
media_type: "image/png".into(),
uri: "asset://provider.muninn/board.png".into(),
width: count(640),
height: count(360),
}],
};
FixtureSet {
surfaces: vec![surface(provider, "input-target", root, vec![])],
catalogs: vec![catalog],
..FixtureSet::default()
}
.sorted()
}
fn form() -> FixtureSet {
let provider = "provider.settings";
let toggle = Node::Toggle(ToggleNode {
common: common("enabled"),
checked: BoolSource::Bound(record_member(provider, "settings", "current", &["Enabled"])),
on_change: command("save"),
});
let slider = Node::Slider(SliderNode {
common: common("volume"),
min: 0.0,
max: 1.0,
step: 0.05,
value: NumberSource::Bound(record_member(provider, "settings", "current", &["Volume"])),
commit: command("save"),
});
let select = Node::Select(SelectNode {
common: common("theme"),
options: OptionList::Literal(LiteralOptions {
options: vec![
SelectOption { value: "dark".into(), label: "Dark".into() },
SelectOption { value: "light".into(), label: "Light".into() },
],
}),
value: record_member(provider, "settings", "current", &["Theme"]),
on_change: command("save"),
});
let port = text_input("port", InputKind::Number, "8080", command("save"));
let root = boxed("root", vec![toggle, slider, select, port]);
let form = surface(provider, "form", root, vec![decl("save", &["enabled", "volume", "theme", "port"], None)]);
let invocation = invoke(
&form,
"0b7e44aa-31c9-4e0d-a6f2-95d8c3e1b277",
"save",
vec![
captured("enabled", InputValue::Bool(BoolValue { value: true })),
captured("volume", InputValue::Number(NumberValue { value: 0.75 })),
captured("theme", InputValue::Choice(ChoiceValue { value: "dark".into() })),
captured("port", InputValue::Number(NumberValue { value: 8080.0 })),
],
);
// The save succeeds and clears the drafts the invocation captured.
let result = CommandResult::completed(&invocation, seq(1), Some(ver(2)), true, None);
FixtureSet { surfaces: vec![form], invocations: vec![invocation], results: vec![result], ..FixtureSet::default() }
.sorted()
}
fn modal_overlay() -> SurfaceDocument {
let dialog = Node::Box(BoxNode {
common: common("dialog"),
style: style(),
paint: plain_paint(),
role: Role::Dialog,
children: vec![
text("dialog-title", "Delete the archive?"),
button("confirm", "Delete", command("confirm")),
button("cancel", "Cancel", command("dismiss")),
],
});
let overlay = Node::Overlay(OverlayNode {
common: common("confirm-overlay"),
anchor: Anchor::Viewport,
modal: true,
dismiss: command("dismiss"),
children: vec![dialog],
});
surface(
"provider.dialog",
"modal",
boxed("root", vec![text("page-text", "The archive holds 12 items."), overlay]),
vec![decl("confirm", &[], Some("Delete the archive?")), decl("dismiss", &[], None)],
)
}
fn scroll_list() -> SurfaceDocument {
let provider = "provider.feed";
let row = Node::Box(BoxNode {
common: common("item-row"),
style: style(),
paint: plain_paint(),
role: Role::ListItem,
children: vec![Node::Text(TextNode {
common: common("item-title"),
content: TextSource::Bound(item_bind(path(&["Title"]))),
style_token: "body".into(),
wrap: false,
max_lines: Some(count(1)),
selectable: false,
})],
});
let items = Node::Repeat(RepeatNode {
common: common("items"),
collection: CollectionSource::Records(RecordsSource {
provider: Some(ProviderId::new(provider)),
schema: SchemaId::new(format!("{TEST_SCHEMA_ROOT}.item.v1")),
key_prefix: "item-".into(),
}),
key_member: path(&["Id"]),
template: std::boxed::Box::new(row),
});
let mut list = style();
list.overflow = Overflow::Scroll;
list.size = size2(Dimension::Percent(Scalar { value: 100.0 }), px(400.0));
let root = Node::Box(BoxNode {
common: common("root"),
style: list,
paint: plain_paint(),
role: Role::List,
children: vec![items],
});
surface(provider, "scroll-list", root, vec![])
}
fn plot() -> SurfaceDocument {
let provider = "provider.market";
let series = || record_member(provider, "series", "prices", &["Values"]);
let mark = |id: &str, mark: PlotMark, x: (Option<f64>, Option<f64>), y: (Option<f64>, Option<f64>)| {
Node::Plot(PlotNode {
common: common(id),
series: series(),
mark,
x_min: x.0,
x_max: x.1,
y_min: y.0,
y_max: y.1,
})
};
let root = boxed(
"root",
vec![
mark("line", PlotMark::Line, (None, None), (None, None)),
mark("bar", PlotMark::Bar, (None, None), (Some(0.0), None)),
mark("area", PlotMark::Area, (Some(0.0), Some(99.0)), (Some(-1.0), Some(1.0))),
],
);
surface(provider, "plot", root, vec![])
}
fn embed_viewport() -> SurfaceDocument {
let embed = Node::Embed(EmbedNode {
common: common("viewport"),
slot_kind: "viewport.world".into(),
slot_id: "main".into(),
width: 320.0,
height: 180.0,
});
let mut row = style();
row.direction = Direction::Row;
let root = Node::Box(BoxNode {
common: common("root"),
style: row,
paint: plain_paint(),
role: Role::Group,
children: vec![text("before", "before"), embed, text("after", "after")],
});
surface("provider.viewport", "embed-viewport", root, vec![])
}
/// A chain of `levels` Boxes, each the only child of the last, the innermost empty.
fn deep_surface(levels: usize) -> SurfaceDocument {
let mut chain = boxed(&format!("deep-{}", levels - 1), vec![]);
for level in (0..levels - 1).rev() {
chain = boxed(&format!("deep-{level}"), vec![chain]);
}
surface("provider.deep", "deep", chain, vec![])
}
/// The most Box levels whose surface payload CultCache's depth check accepts, found by trying
/// one more level until the check refuses. The bound is CultCache's, never restated here.
fn deepest_accepted() -> usize {
let mut levels = 1;
while check_payload_depth(&rmp_serde::to_vec(&deep_surface(levels + 1)).unwrap()).is_ok() {
levels += 1;
}
levels
}
fn text_edge() -> SurfaceDocument {
let paragraph = "The quick brown fox jumps over the lazy dog while the evening light slides across the \
valley, and the long paragraph keeps going so that any reasonable column must break it \
across several lines. "
.repeat(4);
let samples = [
// Hebrew and Arabic runs inside a Latin sentence.
("bidi", "Hello \u{5e9}\u{5dc}\u{5d5}\u{5dd} \u{5e2}\u{5d5}\u{5dc}\u{5dd} and \u{645}\u{631}\u{62d}\u{628}\u{627} \u{628}\u{627}\u{644}\u{639}\u{627}\u{644}\u{645} then 123 end."),
// Han, kana, hangul and fullwidth Latin: two columns each.
("cjk", "\u{65e5}\u{672c}\u{8a9e}\u{30c6}\u{30b9}\u{30c8} \u{4f60}\u{597d}\u{4e16}\u{754c} \u{d55c}\u{ad6d}\u{c5b4} \u{ff21}\u{ff22}\u{ff23}\u{ff11}\u{ff12}\u{ff13}"),
// Marks that attach to the letter before them.
("combining", "e\u{301} a\u{308} n\u{303} o\u{302}\u{323} z\u{35b}\u{34f}\u{300}"),
// A family, a skin-toned technologist and a flag, each one cluster of joined scalars.
("emoji-zwj", "\u{1f469}\u{200d}\u{1f469}\u{200d}\u{1f467}\u{200d}\u{1f466} \u{1f468}\u{1f3fd}\u{200d}\u{1f4bb} \u{1f3f3}\u{fe0f}\u{200d}\u{1f308}"),
("long-wrap", paragraph.as_str()),
];
let nodes = samples
.iter()
.map(|(id, content)| {
Node::Text(TextNode {
common: common(id),
content: lit_text(content),
style_token: "body".into(),
wrap: true,
max_lines: None,
selectable: true,
})
})
.collect();
surface("provider.text", "text-edge", boxed("root", nodes), vec![])
}

View file

@ -0,0 +1,32 @@
//! The one bless door. `THING_BLESS=1` writes; any other run compares and never writes.
use std::path::Path;
fn blessing() -> bool {
std::env::var("THING_BLESS").as_deref() == Ok("1")
}
/// Bless the file or compare against it. Returns the committed bytes. A mismatch panics naming
/// the file and leaves it unchanged.
pub fn check(dir: &Path, file: &str, produced: &[u8]) -> Vec<u8> {
let path = dir.join(file);
if blessing() {
std::fs::write(&path, produced).unwrap_or_else(|error| panic!("{file}: {error}"));
}
let committed = std::fs::read(&path).unwrap_or_else(|error| panic!("{file}: {error}"));
assert_eq!(committed, produced, "{file}: the committed golden differs from what the crate writes");
committed
}
/// Bless or compare `stem.bin` and `stem.txt` together: the binary is the oracle, the text is
/// compared too so it cannot rot. Returns the committed binary.
pub fn check_with_text(dir: &Path, stem: &str, bytes: &[u8], text: &str) -> Vec<u8> {
let committed = check(dir, &format!("{stem}.bin"), bytes);
check(dir, &format!("{stem}.txt"), text.as_bytes());
committed
}
/// Read a committed file. Never writes: backends read core's goldens through this.
pub fn read(dir: &Path, file: &str) -> Vec<u8> {
std::fs::read(dir.join(file)).unwrap_or_else(|error| panic!("{file}: {error}"))
}

View file

@ -0,0 +1,9 @@
//! The fakes, builders and the one bless door the Thing crates test with. A test crate
//! depends on this; no shipped crate does.
pub mod build;
pub mod fixture;
pub mod golden;
pub mod mem_state;
pub mod state;
pub mod store;

View file

@ -0,0 +1,402 @@
//! `MemState`: an in-memory `StatePort`. Each provider's records live in a CultCache with the
//! contract registered, so a typed value and a raw payload meet one decode door. A payload the
//! contract refuses is never stored: the address becomes refused, and stays refused until a
//! record or a delete replaces it.
//!
//! A provider's own state (any schema outside the contract) is held per (provider, key), one record
//! per key as CultCache holds them, already decoded by `thing_state::decode` with
//! the schema's catalog member rows. A payload that decode refuses is held as a refusal.
use std::cell::RefCell;
use std::collections::HashMap;
use std::path::Path;
use cultcache_rs::{
CacheBackingStore, CultCache, CultCacheEnvelope, DatabaseEntry, SchemaCatalogMember, SingleFileMessagePackBackingStore,
resolve_schema_entry,
};
use thing_contract::*;
use thing_state::decode;
use thing_core::port::{
Address, Change, Entry, Interest, Lookup, Prefix, Record, Refusal, StatePort, StateValue, SubscriptionId,
};
use crate::store;
/// A contract kind the port carries.
pub trait StateKind: DatabaseEntry {
fn record_key(&self) -> String;
fn into_record(self) -> Record;
}
macro_rules! state_kinds {
($($kind:ident => $arm:ident),* $(,)?) => {
$(impl StateKind for $kind {
fn record_key(&self) -> String {
$kind::record_key(self)
}
fn into_record(self) -> Record {
Record::$arm(self)
}
})*
};
}
state_kinds!(
SurfaceDocument => Surface,
CompositionDocument => Composition,
CommandResult => Result,
AssetCatalog => Catalog,
);
/// Run `$body` with `$t` bound to the contract kind whose schema is `$schema`, or `$none` for
/// a schema the port does not carry.
macro_rules! by_schema {
($schema:expr, $t:ident => $body:expr, else $none:expr) => {
match $schema {
SurfaceDocument::SCHEMA_NAME => {
type $t = SurfaceDocument;
$body
}
CompositionDocument::SCHEMA_NAME => {
type $t = CompositionDocument;
$body
}
CommandResult::SCHEMA_NAME => {
type $t = CommandResult;
$body
}
AssetCatalog::SCHEMA_NAME => {
type $t = AssetCatalog;
$body
}
_ => $none,
}
};
}
/// One call the port received.
#[derive(Clone, Debug, PartialEq)]
pub enum Call {
Read(Address),
List(Prefix),
Subscribe(Interest),
Unsubscribe(SubscriptionId),
Drain,
}
/// What a provider key holds of provider state.
#[derive(Clone)]
enum Held {
Value { schema: SchemaId, value: StateValue },
Refused(Refusal),
}
impl Held {
fn schema(&self) -> &SchemaId {
match self {
Held::Value { schema, .. } => schema,
Held::Refused(refusal) => &refusal.kind,
}
}
}
/// The schema id of the contract kind whose CultCache entry type is `entry_type`.
fn contract_schema(entry_type: &str) -> Option<&'static str> {
[
(SurfaceDocument::TYPE, SurfaceDocument::SCHEMA_NAME),
(CompositionDocument::TYPE, CompositionDocument::SCHEMA_NAME),
(CommandResult::TYPE, CommandResult::SCHEMA_NAME),
(AssetCatalog::TYPE, AssetCatalog::SCHEMA_NAME),
]
.into_iter()
.find_map(|(entry, schema)| (entry == entry_type).then_some(schema))
}
fn is_contract(schema: &SchemaId) -> bool {
by_schema!(schema.as_str(), _T => true, else false)
}
pub struct MemState {
providers: HashMap<String, CultCache>,
state: HashMap<(String, String), Held>,
refused: HashMap<Address, Refusal>,
interests: Vec<(SubscriptionId, Interest)>,
next_subscription: u64,
queue: Vec<Change>,
calls: RefCell<Vec<Call>>,
}
impl Default for MemState {
fn default() -> Self {
Self::new()
}
}
impl MemState {
pub fn new() -> Self {
Self {
providers: HashMap::new(),
state: HashMap::new(),
refused: HashMap::new(),
interests: Vec::new(),
next_subscription: 0,
queue: Vec::new(),
calls: RefCell::new(Vec::new()),
}
}
/// A state holding every document of a fixture, each under the provider that publishes it.
pub fn from_fixture(fixture: crate::fixture::Fixture) -> Self {
let set = fixture.load();
let mut state = Self::new();
for surface in &set.surfaces {
state.put(&surface.provider_id, surface);
}
for composition in &set.compositions {
state.put(&ProviderId::new(composition.publisher.clone()), composition);
}
for catalog in &set.catalogs {
state.put(&catalog.provider_id, catalog);
}
state
}
/// Store a record under its record key at `provider`.
pub fn put<T: StateKind>(&mut self, provider: &ProviderId, value: &T) {
let address = Address {
provider: provider.clone(),
schema: SchemaId::new(T::SCHEMA_NAME),
key: RecordKey::new(value.record_key()),
};
let outcome = self.cache(provider).put(address.key.as_str(), value);
self.admit::<T>(address, outcome);
}
/// Store a payload under `address`; the address's schema names the contract kind. A payload
/// the contract refuses makes the address refused.
pub fn put_raw(&mut self, address: Address, payload: Vec<u8>) {
by_schema!(address.schema.as_str(), T => {
let envelope = CultCacheEnvelope {
key: address.key.as_str().into(),
r#type: T::TYPE.into(),
payload,
stored_at: store::PINNED_CLOCK.into(),
schema_id: Some(T::SCHEMA_NAME.into()),
};
let outcome = self.cache(&address.provider).put_envelope::<T>(envelope);
self.admit::<T>(address, outcome);
}, else panic!("no contract record kind has schema {}", address.schema.as_str()))
}
/// Store provider state `value` under `key` at `provider`: the type's own schema and member
/// rows decode it, as a store written by this type would.
pub fn put_state<T: DatabaseEntry>(&mut self, provider: &ProviderId, key: &str, value: &T) {
assert_eq!(
T::TYPE,
T::SCHEMA_NAME,
"a provider state type must be registered with its entry type equal to its schema id"
);
let mut cache = CultCache::new();
cache.register_entry_type::<T>().unwrap();
let payload = cache.prepare_entry(key, value).unwrap().0.payload;
let address = Address { provider: provider.clone(), schema: SchemaId::new(T::SCHEMA_NAME), key: RecordKey::new(key) };
self.put_state_raw(address, payload, &T::schema_members());
}
/// Store a provider-state payload under `address`, decoded with the schema's member `rows`.
/// A payload decode refuses makes the key refused, replacing any record it held.
pub fn put_state_raw(&mut self, address: Address, payload: Vec<u8>, rows: &[SchemaCatalogMember]) {
assert!(!is_contract(&address.schema), "{} is a contract kind: put_raw", address.schema.as_str());
let slot = (address.provider.as_str().to_string(), address.key.as_str().to_string());
match decode(&payload, rows) {
Ok(value) => {
let schema = address.schema.clone();
self.state.insert(slot, Held::Value { schema: schema.clone(), value: value.clone() });
self.queue(Change::Upsert(Entry { address, record: Record::State { schema, value } }));
}
Err(error) => {
let detail = format!("{}: {error}", address.schema.as_str());
let refusal = Refusal { kind: address.schema.clone(), address, detail };
self.state.insert(slot, Held::Refused(refusal.clone()));
self.queue(Change::Refused(refusal));
}
}
}
/// Read a single-file store, routing each record: a contract kind to `put_raw`, anything else
/// to `put_state_raw` with the member rows the store's own catalog publishes for its schema.
/// The store is read from a copy, so the file and its directory are never written.
pub fn load_store(&mut self, provider: &ProviderId, path: &Path) {
let work = store::scratch_dir("load");
let copy = work.join("store.cc");
std::fs::copy(path, &copy).unwrap();
let backing = SingleFileMessagePackBackingStore::new(&copy);
let catalog = backing.pull_schema_catalog().unwrap();
let mut envelopes = backing.pull_all().unwrap();
drop(backing);
let _ = std::fs::remove_dir_all(&work);
envelopes.sort_by(|a, b| a.key.cmp(&b.key));
for envelope in envelopes {
// A store names a record's schema by its entry type: a contract kind's type maps to
// its schema id, and any other type is the schema id of provider state.
let key = RecordKey::new(envelope.key);
if let Some(schema) = contract_schema(&envelope.r#type) {
self.put_raw(Address { provider: provider.clone(), schema: SchemaId::new(schema), key }, envelope.payload);
} else {
let schema = envelope.schema_id.unwrap_or(envelope.r#type);
let rows = resolve_schema_entry(&catalog, &schema).map(|entry| entry.members.clone());
let address = Address { provider: provider.clone(), schema: SchemaId::new(schema), key };
self.put_state_raw(address, envelope.payload, &rows.unwrap_or_default());
}
}
}
/// Remove the record or the refusal at `address`; removing nothing is not a change.
pub fn delete(&mut self, address: &Address) {
if !is_contract(&address.schema) {
let slot = (address.provider.as_str().to_string(), address.key.as_str().to_string());
if self.state.get(&slot).is_some_and(|held| held.schema() == &address.schema) {
self.state.remove(&slot);
self.queue(Change::Delete(address.clone()));
}
return;
}
let refused = self.refused.remove(address).is_some();
let stored = by_schema!(address.schema.as_str(), T => {
match self.providers.get_mut(address.provider.as_str()) {
Some(cache) => cache.delete::<T>(address.key.as_str()).unwrap(),
None => false,
}
}, else false);
if refused || stored {
self.queue(Change::Delete(address.clone()));
}
}
/// Every call the port received, in order.
pub fn calls(&self) -> Vec<Call> {
self.calls.borrow().clone()
}
fn cache(&mut self, provider: &ProviderId) -> &mut CultCache {
self.providers.entry(provider.as_str().to_string()).or_insert_with(store::memory)
}
fn admit<T: StateKind>(&mut self, address: Address, outcome: anyhow::Result<T>) {
match outcome {
Ok(value) => {
self.refused.remove(&address);
self.queue(Change::Upsert(Entry { address, record: value.into_record() }));
}
Err(error) => {
// The address is now refused: an older valid record under it no longer stands.
self.cache(&address.provider).delete::<T>(address.key.as_str()).unwrap();
let refusal =
Refusal { address: address.clone(), kind: address.schema.clone(), detail: format!("{error:#}") };
self.refused.insert(address, refusal.clone());
self.queue(Change::Refused(refusal));
}
}
}
fn queue(&mut self, change: Change) {
let address = match &change {
Change::Upsert(entry) => &entry.address,
Change::Delete(address) => address,
Change::Refused(refusal) => &refusal.address,
};
if self.interests.iter().any(|(_, interest)| interest.matches(address)) {
self.queue.push(change);
}
}
}
impl StatePort for MemState {
fn read(&self, address: &Address) -> Lookup {
self.calls.borrow_mut().push(Call::Read(address.clone()));
if !is_contract(&address.schema) {
return match self.state.get(&(address.provider.as_str().to_string(), address.key.as_str().to_string())) {
Some(Held::Value { schema, value }) => Lookup::Present(Entry {
address: address.clone(),
record: Record::State { schema: schema.clone(), value: value.clone() },
}),
Some(Held::Refused(refusal)) => Lookup::Refused(refusal.clone()),
None => Lookup::Absent,
};
}
if let Some(refusal) = self.refused.get(address) {
return Lookup::Refused(refusal.clone());
}
by_schema!(address.schema.as_str(), T => {
let stored = self.providers.get(address.provider.as_str());
match stored.and_then(|cache| cache.get::<T>(address.key.as_str()).expect("stored records decode")) {
Some(value) => Lookup::Present(Entry { address: address.clone(), record: value.into_record() }),
None => Lookup::Absent,
}
}, else unreachable!("is_contract admitted the schema"))
}
fn list(&self, prefix: &Prefix) -> Vec<Lookup> {
self.calls.borrow_mut().push(Call::List(prefix.clone()));
let at = |key: &str| Address {
provider: prefix.provider.clone(),
schema: prefix.schema.clone(),
key: RecordKey::new(key),
};
let mut found: Vec<(String, Lookup)> = self
.refused
.values()
.filter(|refusal| prefix.matches(&refusal.address))
.map(|refusal| (refusal.address.key.as_str().to_string(), Lookup::Refused(refusal.clone())))
.collect();
if !is_contract(&prefix.schema) {
for ((provider, key), held) in &self.state {
if provider != prefix.provider.as_str() || !key.starts_with(&prefix.key_prefix) {
continue;
}
match held {
Held::Value { schema, value } if schema == &prefix.schema => {
let record = Record::State { schema: schema.clone(), value: value.clone() };
found.push((key.clone(), Lookup::Present(Entry { address: at(key), record })));
}
Held::Refused(refusal) if refusal.kind == prefix.schema => {
found.push((key.clone(), Lookup::Refused(refusal.clone())));
}
_ => {}
}
}
} else {
by_schema!(prefix.schema.as_str(), T => {
if let Some(cache) = self.providers.get(prefix.provider.as_str()) {
for (key, value) in cache.get_all_with_keys::<T>().expect("stored records decode") {
if key.starts_with(&prefix.key_prefix) {
let entry = Entry { address: at(&key), record: value.into_record() };
found.push((key, Lookup::Present(entry)));
}
}
}
}, else unreachable!("is_contract admitted the schema"));
}
found.sort_by(|a, b| a.0.cmp(&b.0));
found.into_iter().map(|(_, lookup)| lookup).collect()
}
fn subscribe(&mut self, interest: Interest) -> SubscriptionId {
self.calls.borrow_mut().push(Call::Subscribe(interest.clone()));
let id = SubscriptionId(self.next_subscription);
self.next_subscription += 1;
self.interests.push((id, interest));
id
}
fn unsubscribe(&mut self, id: SubscriptionId) {
self.calls.borrow_mut().push(Call::Unsubscribe(id));
self.interests.retain(|(live, _)| *live != id);
}
fn drain(&mut self) -> Vec<Change> {
self.calls.borrow_mut().push(Call::Drain);
std::mem::take(&mut self.queue)
}
}

View file

@ -0,0 +1,157 @@
//! The provider state the fixtures bind: test schemas whose Rust field names, PascalCased, are
//! the member names the fixtures read, and the script that fills a `MemState` with each
//! fixture's records. Fixture builders name these schemas by id; none of them is a contract kind.
//!
//! A CultCache store names a record's schema by its entry type, not by `SCHEMA_NAME`, so each type
//! here is registered under its schema id: the id a Bind names is the id the store holds.
use cultcache_rs::DatabaseEntry;
use serde::{Deserialize, Serialize};
use thing_contract::{ProviderId, RecordKey, SchemaId};
use thing_core::port::Address;
use crate::fixture::Fixture;
use crate::mem_state::MemState;
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
#[cultcache(type = "gamecult.thing.test.swarm.v1", schema = "gamecult.thing.test.swarm.v1")]
pub struct Swarm {
#[cultcache(key = 0)]
pub id: String,
#[cultcache(key = 1)]
pub name: String,
#[cultcache(key = 2)]
pub load: f64,
}
/// `Swarm`'s twin as today's hand-written crates publish it: the same type, schema and bytes,
/// and no member rows.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SwarmWithoutRows {
pub id: String,
pub name: String,
pub load: f64,
}
impl DatabaseEntry for SwarmWithoutRows {
const TYPE: &'static str = "gamecult.thing.test.swarm.v1";
const SCHEMA_NAME: &'static str = "gamecult.thing.test.swarm.v1";
}
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
#[cultcache(type = "gamecult.thing.test.target.v1", schema = "gamecult.thing.test.target.v1")]
pub struct Target {
#[cultcache(key = 0)]
pub label: String,
}
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
#[cultcache(type = "gamecult.thing.test.settings.v1", schema = "gamecult.thing.test.settings.v1")]
pub struct Settings {
#[cultcache(key = 0)]
pub enabled: bool,
#[cultcache(key = 1)]
pub volume: f64,
#[cultcache(key = 2)]
pub theme: String,
}
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
#[cultcache(type = "gamecult.thing.test.item.v1", schema = "gamecult.thing.test.item.v1")]
pub struct Item {
#[cultcache(key = 0)]
pub id: String,
#[cultcache(key = 1)]
pub title: String,
}
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
#[cultcache(type = "gamecult.thing.test.series.v1", schema = "gamecult.thing.test.series.v1")]
pub struct Series {
#[cultcache(key = 0)]
pub values: Vec<f64>,
}
/// The swarm records of f01 and, under the hostile provider, f10's: the three minds and the
/// summary.
pub fn swarm_records() -> Vec<(&'static str, Swarm)> {
let swarm = |id: &str, name: &str, load: f64| Swarm { id: id.into(), name: name.into(), load };
vec![
("summary", swarm("summary", "Swarm", 0.42)),
("mind-1", swarm("mind-1", "Eureka", 0.31)),
("mind-2", swarm("mind-2", "Libby", 0.57)),
("mind-3", swarm("mind-3", "Kiko", 0.08)),
]
}
/// Fill `state` with the provider records `fixture`'s surfaces bind. A fixture that binds no
/// provider state adds nothing.
pub fn script(fixture: Fixture, state: &mut MemState) {
match fixture {
Fixture::F01SwarmDashboard => {
let provider = ProviderId::new("provider.swarm");
for (key, swarm) in swarm_records() {
state.put_state(&provider, key, &swarm);
}
}
Fixture::F03InputTarget => {
state.put_state(&ProviderId::new("provider.muninn"), "cursor", &Target { label: "Ready".into() });
}
Fixture::F04Form => {
let settings = Settings { enabled: true, volume: 40.0, theme: "dark".into() };
state.put_state(&ProviderId::new("provider.settings"), "current", &settings);
}
Fixture::F06ScrollList => {
let provider = ProviderId::new("provider.feed");
for n in 0..1000 {
let id = format!("item-{n:04}");
state.put_state(&provider, &id, &Item { id: id.clone(), title: format!("Item {n}") });
}
}
Fixture::F07Plot => {
let series = Series { values: vec![3.0, 5.5, 4.25, 8.0, 6.5] };
state.put_state(&ProviderId::new("provider.market"), "prices", &series);
}
Fixture::F10Hostile => {
// A swarm record where the hostile surface's Bind asks for nowhere.v1.
let swarm = Swarm { id: "row-1".into(), name: "Elsewhere".into(), load: 0.0 };
state.put_state(&ProviderId::new("provider.hostile"), "row-1", &swarm);
}
_ => {}
}
}
/// The address of a record of `schema` at `provider` and `key`.
pub fn address(provider: &str, schema: &str, key: &str) -> Address {
Address { provider: ProviderId::new(provider), schema: SchemaId::new(schema), key: RecordKey::new(key) }
}
/// The committed store of f01's swarm records, written with `Swarm` registered: its schema
/// publishes member rows.
pub const SWARM_STORE: &str = "state-swarm.state.cc";
/// The same records written through `SwarmWithoutRows`: the schema publishes `[]`.
pub const SWARM_STORE_MEMBERS_EMPTY: &str = "state-swarm-members-empty.state.cc";
/// Bless or compare the committed swarm store; returns the committed bytes.
pub fn write_swarm_store() -> Vec<u8> {
let bytes = crate::store::bytes(|cache| {
cache.register_entry_type::<Swarm>().unwrap();
for (key, swarm) in swarm_records() {
crate::store::put_pinned(cache, key, &swarm);
}
});
crate::golden::check(&Fixture::dir(), SWARM_STORE, &bytes)
}
/// Bless or compare the committed members-`[]` swarm store; returns the committed bytes.
pub fn write_swarm_store_members_empty() -> Vec<u8> {
let bytes = crate::store::bytes(|cache| {
cache.register_entry_type::<SwarmWithoutRows>().unwrap();
for (key, swarm) in swarm_records() {
let twin = SwarmWithoutRows { id: swarm.id, name: swarm.name, load: swarm.load };
crate::store::put_pinned(cache, key, &twin);
}
});
crate::golden::check(&Fixture::dir(), SWARM_STORE_MEMBERS_EMPTY, &bytes)
}

View file

@ -0,0 +1,70 @@
//! CultCache single-file stores of contract documents, written under a pinned clock so the
//! bytes are reproducible.
use std::path::{Path, PathBuf};
use cultcache_rs::{CultCache, CultCacheRegistry, DatabaseEntry, SingleFileMessagePackBackingStore};
use thing_contract::ThingContract;
pub const PINNED_CLOCK: &str = "2026-01-01T00:00:00Z";
/// A cache with the contract registered and no backing store.
pub fn memory() -> CultCache {
let mut cache = CultCache::new();
ThingContract.register_entries(&mut cache).unwrap();
cache
}
/// An empty cache with the contract registered over a fresh single-file store at `path`.
pub fn create(path: &Path) -> CultCache {
let _ = std::fs::remove_file(path);
let mut cache = memory();
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(path)).unwrap();
// From cultcache-rs 0.4 a cache that attached a store refuses writes until it pulls; the file
// was just removed, so the pull is empty.
cache.pull_all_backing_stores().unwrap();
cache
}
/// Store `value` under `key` with `stored_at` pinned.
pub fn put_pinned<T: DatabaseEntry>(cache: &mut CultCache, key: &str, value: &T) {
let (mut envelope, _) = cache.prepare_entry(key, value).unwrap();
envelope.stored_at = PINNED_CLOCK.into();
cache.put_envelope::<T>(envelope).unwrap();
}
/// A cache with the contract registered, pulled from the store at `path`.
pub fn open(path: &Path) -> CultCache {
let mut cache = memory();
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(path)).unwrap();
cache.pull_all_backing_stores().unwrap();
cache
}
/// A fresh directory of its own under the temp directory (process id and a serial), so the lock
/// file a store creates beside its file goes when the directory does.
pub(crate) fn scratch_dir(purpose: &str) -> PathBuf {
static SERIAL: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let serial = SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let work = std::env::temp_dir().join(format!("thing-testkit-{purpose}-{}-{serial}", std::process::id()));
std::fs::create_dir_all(&work).unwrap();
work
}
/// The bytes of a scratch single-file store that `fill` filled under the pinned clock. The scratch
/// store and its lock file are removed.
pub fn bytes(fill: impl FnOnce(&mut CultCache)) -> Vec<u8> {
let work = scratch_dir("write");
let scratch = work.join("store.cc");
let mut cache = create(&scratch);
fill(&mut cache);
drop(cache);
let bytes = std::fs::read(&scratch).unwrap();
let _ = std::fs::remove_dir_all(&work);
bytes
}
/// The payload the contract writes for `value`, as a store would hold it.
pub fn payload<T: DatabaseEntry>(value: &T) -> Vec<u8> {
memory().prepare_entry("payload", value).unwrap().0.payload
}

View file

@ -0,0 +1,480 @@
//! The committed fixture stores: they open through the contract, the builders reproduce them
//! byte for byte, and each holds the shapes its row of the fixture table names.
//! `THING_BLESS=1` on this test rewrites them; any other run compares.
use cultcache_rs::{CultCacheEnvelope, PayloadTooDeep, check_payload_depth};
use thing_contract::*;
use thing_testkit::fixture::{Fixture, FixtureSet};
use thing_testkit::golden;
use thing_testkit::mem_state::MemState;
use thing_testkit::store;
use thing_core::port::{Address, Lookup, StatePort};
fn load(fixture: Fixture) -> FixtureSet {
fixture.load()
}
#[test]
fn every_fixture_round_trips_through_the_contract() {
for fixture in Fixture::ALL {
// The builders reproduce the committed file byte for byte (or bless it).
let committed = fixture.write();
assert_eq!(committed, std::fs::read(Fixture::dir().join(fixture.file_name())).unwrap());
assert!(!committed.is_empty());
let built = fixture.build();
let loaded = fixture.load();
assert_eq!(loaded, built, "{}: the store decodes to the built documents", fixture.file_name());
// Each record re-encodes to its stored payload.
let cache = fixture.open();
let stored = cache.snapshot_envelopes();
let payload = |kind: &str, key: String| {
stored.iter().find(|envelope| envelope.r#type == kind && envelope.key == key).unwrap().payload.clone()
};
for surface in &loaded.surfaces {
assert_eq!(rmp_serde::to_vec(surface).unwrap(), payload("gamecult.thing.surface", surface.record_key()));
}
for composition in &loaded.compositions {
let key = composition.record_key();
assert_eq!(rmp_serde::to_vec(composition).unwrap(), payload("gamecult.thing.composition", key));
}
for catalog in &loaded.catalogs {
assert_eq!(rmp_serde::to_vec(catalog).unwrap(), payload("gamecult.thing.asset_catalog", catalog.record_key()));
}
for invocation in &loaded.invocations {
let key = invocation.record_key();
assert_eq!(rmp_serde::to_vec(invocation).unwrap(), payload("gamecult.thing.command_invocation", key));
}
for result in &loaded.results {
assert_eq!(rmp_serde::to_vec(result).unwrap(), payload("gamecult.thing.command_result", result.record_key()));
}
assert_eq!(
stored.len(),
loaded.document_count(),
"{}: the store holds the documents and nothing else",
fixture.file_name()
);
}
// The payload one Box level past f11's chain is a raw file, not a store.
assert_eq!(Fixture::write_deep_refused(), Fixture::deep_refused_payload());
}
fn commands_declared(surface: &SurfaceDocument) -> Vec<&str> {
surface.commands.iter().map(|decl| decl.id.as_str()).collect()
}
fn box_children(node: &Node) -> &[Node] {
match node {
Node::Box(node) => &node.children,
other => panic!("not a Box: {other:?}"),
}
}
#[test]
fn f01_is_the_swarm_dashboard() {
let set = load(Fixture::F01SwarmDashboard);
assert_eq!(set.surfaces.len(), 1);
let surface = &set.surfaces[0];
let Node::Box(root) = &surface.root else { panic!("root is not a Box") };
assert_eq!(root.style.display, Display::Grid);
let [load, minds, restart] = &root.children[..] else { panic!("three children expected") };
let Node::Text(load) = load else { panic!("not a Text") };
let TextSource::Bound(bind) = &load.content else { panic!("Text is not bound") };
assert!(matches!(bind.format, Some(Format::Number(_))));
let Node::Repeat(minds) = minds else { panic!("not a Repeat") };
assert!(matches!(minds.collection, CollectionSource::Records(_)));
let Node::Button(restart) = restart else { panic!("not a Button") };
let CommandRef::Id(command) = &restart.on_activate else { panic!("not a command id") };
assert_eq!(commands_declared(surface), [command.id.as_str()]);
}
#[test]
fn f09_stacks_compositions_with_every_argument_arm() {
let set = load(Fixture::F09CompositionStack);
assert_eq!((set.surfaces.len(), set.compositions.len()), (1, 1));
let surface = &set.surfaces[0];
let [std_stat, outer] = box_children(&surface.root) else { panic!("two Uses expected") };
let Node::Use(std_stat) = std_stat else { panic!("not a Use") };
assert_eq!((std_stat.composition.publisher.as_str(), std_stat.composition.name.as_str()), ("thing.std", "stat"));
let Node::Use(outer) = outer else { panic!("not a Use") };
assert_eq!(outer.composition.publisher, set.compositions[0].publisher);
assert_eq!(outer.composition.name, set.compositions[0].name);
assert_eq!(outer.composition.version, set.compositions[0].version);
let arms: Vec<&str> = outer
.args
.iter()
.map(|arg| match arg.value {
ArgValue::Text(_) => "text",
ArgValue::Number(_) => "number",
ArgValue::Bool(_) => "bool",
ArgValue::Bind(_) => "bind",
ArgValue::Collection(_) => "collection",
ArgValue::Command(_) => "command",
ArgValue::Slot(_) => "slot",
})
.collect();
assert_eq!(arms, ["text", "number", "bool", "bind", "collection", "command", "slot"]);
// The slot holds a second Use of the same composition: two levels.
let ArgValue::Slot(slot) = &outer.args[6].value else { unreachable!() };
assert!(slot.nodes.iter().any(|node| matches!(node, Node::Use(inner) if inner.composition == outer.composition)));
}
#[test]
fn f10_holds_exactly_the_four_hostile_surfaces() {
let set = load(Fixture::F10Hostile);
let labels: Vec<&str> = set.surfaces.iter().map(|surface| surface.label.as_str()).collect();
assert_eq!(labels, ["duplicate-id", "schema-mismatch", "undeclared-command", "unresolved-use"]);
let by = |label: &str| set.surfaces.iter().find(|surface| surface.label.as_str() == label).unwrap();
let undeclared = by("undeclared-command");
let Node::Button(button) = &box_children(&undeclared.root)[0] else { panic!("not a Button") };
let CommandRef::Id(command) = &button.on_activate else { panic!("not a command id") };
assert!(!commands_declared(undeclared).contains(&command.id.as_str()));
// The composition emits `shared-id`, which expands to `dup-use/shared-id`: the surface authors that id.
let dup = by("duplicate-id");
let children = box_children(&dup.root);
assert!(children.iter().any(|node| matches!(node, Node::Text(text) if text.common.id.as_str() == "dup-use/shared-id")));
let Node::Use(used) = &children[0] else { panic!("not a Use") };
let composition = set.compositions.iter().find(|composition| composition.name == used.composition.name).unwrap();
assert!(box_children(&composition.body).iter().any(|node| matches!(node, Node::Text(text) if text.common.id.as_str() == "shared-id")));
// The unresolved Use names a composition no document holds.
let Node::Use(ghost) = &box_children(&by("unresolved-use").root)[0] else { panic!("not a Use") };
assert!(set.compositions.iter().all(|composition| composition.name != ghost.composition.name));
// The Bind names a schema none of the fixtures use for state.
let Node::Text(text) = &box_children(&by("schema-mismatch").root)[0] else { panic!("not a Text") };
let TextSource::Bound(Bind { source: StateSource::Record(state), .. }) = &text.content else {
panic!("Text is not bound to a record")
};
let f01 = load(Fixture::F01SwarmDashboard);
let Node::Box(root) = &f01.surfaces[0].root else { unreachable!() };
let Node::Text(f01_text) = &root.children[0] else { unreachable!() };
let TextSource::Bound(Bind { source: StateSource::Record(f01_state), .. }) = &f01_text.content else { unreachable!() };
assert_ne!(state.schema, f01_state.schema);
}
#[test]
fn a_state_holds_every_fixture_document_under_its_publisher() {
let state = MemState::from_fixture(Fixture::F09CompositionStack);
let set = load(Fixture::F09CompositionStack);
let at = Address {
provider: ProviderId::new(set.compositions[0].publisher.clone()),
schema: SchemaId::new("gamecult.thing.composition.v1"),
key: RecordKey::new(set.compositions[0].record_key()),
};
assert!(matches!(state.read(&at), Lookup::Present(_)));
}
#[test]
fn loading_a_fixture_writes_nothing_in_the_fixtures_directory() {
let listing = || {
let mut names: Vec<_> = std::fs::read_dir(Fixture::dir())
.unwrap()
.map(|entry| entry.unwrap().file_name().into_string().unwrap())
.collect();
names.sort();
names
};
let before = listing();
// Restores the directory's permissions even when the test panics.
struct Restore(std::fs::Permissions);
impl Drop for Restore {
fn drop(&mut self) {
let _ = std::fs::set_permissions(Fixture::dir(), self.0.clone());
}
}
let mut permissions = std::fs::metadata(Fixture::dir()).unwrap().permissions();
let _restore = Restore(permissions.clone());
permissions.set_readonly(true);
std::fs::set_permissions(Fixture::dir(), permissions).unwrap();
for fixture in Fixture::ALL {
load(fixture);
}
assert_eq!(listing(), before);
}
fn arm(node: &Node) -> &'static str {
match node {
Node::Box(_) => "Box",
Node::Text(_) => "Text",
Node::Image(_) => "Image",
Node::Button(_) => "Button",
Node::Toggle(_) => "Toggle",
Node::Slider(_) => "Slider",
Node::TextInput(_) => "TextInput",
Node::Select(_) => "Select",
Node::Repeat(_) => "Repeat",
Node::Overlay(_) => "Overlay",
Node::Plot(_) => "Plot",
Node::Embed(_) => "Embed",
Node::Use(_) => "Use",
Node::Slot(_) => "Slot",
}
}
// The fourteen arms the fixtures place; the Slot stands in f09's composition body.
const ALL_ARMS: [&str; 14] = [
"Box", "Button", "Embed", "Image", "Overlay", "Plot", "Repeat", "Select", "Slider", "Slot", "Text", "TextInput",
"Toggle", "Use",
];
/// Every node under `node`, itself first, through every child position the union has.
fn walk<'a>(node: &'a Node, out: &mut Vec<&'a Node>) {
out.push(node);
match node {
Node::Box(node) => node.children.iter().for_each(|child| walk(child, out)),
Node::Button(node) => node.content.iter().for_each(|child| walk(child, out)),
Node::Repeat(node) => walk(&node.template, out),
Node::Overlay(node) => node.children.iter().for_each(|child| walk(child, out)),
Node::Use(node) => {
for arg in &node.args {
if let ArgValue::Slot(slot) = &arg.value {
slot.nodes.iter().for_each(|child| walk(child, out));
}
}
}
_ => {}
}
}
fn nodes(set: &FixtureSet) -> Vec<&Node> {
let mut out = Vec::new();
set.surfaces.iter().for_each(|surface| walk(&surface.root, &mut out));
set.compositions.iter().for_each(|composition| walk(&composition.body, &mut out));
out
}
fn arms_of(fixture: Fixture) -> std::collections::BTreeSet<&'static str> {
nodes(&load(fixture)).into_iter().map(arm).collect()
}
fn holds(fixture: Fixture, wanted: &[&str]) {
let arms = arms_of(fixture);
for name in wanted {
assert!(arms.contains(name), "{}: no {name} node", fixture.file_name());
}
}
#[test]
fn the_twelve_fixtures_cover_all_fourteen_node_arms() {
let mut covered = std::collections::BTreeSet::new();
for fixture in Fixture::ALL {
covered.extend(arms_of(fixture));
}
assert_eq!(covered.into_iter().collect::<Vec<_>>(), ALL_ARMS);
holds(Fixture::F02LoginEffect, &["TextInput", "Button"]);
holds(Fixture::F03InputTarget, &["Image", "Box", "Text"]);
holds(Fixture::F04Form, &["Toggle", "Slider", "Select", "TextInput"]);
holds(Fixture::F05ModalOverlay, &["Overlay", "Button"]);
holds(Fixture::F06ScrollList, &["Box", "Repeat"]);
holds(Fixture::F07Plot, &["Plot"]);
holds(Fixture::F08EmbedViewport, &["Embed", "Text"]);
holds(Fixture::F11Deep, &["Box"]);
holds(Fixture::F12TextEdge, &["Text"]);
}
fn single_surface(fixture: Fixture) -> (FixtureSet, SurfaceDocument) {
let set = load(fixture);
assert_eq!(set.surfaces.len(), 1, "{}", fixture.file_name());
let surface = set.surfaces[0].clone();
(set, surface)
}
#[test]
fn f02_completes_with_an_external_step_whose_resume_command_the_surface_declares() {
let (set, surface) = single_surface(Fixture::F02LoginEffect);
let [invocation] = &set.invocations[..] else { panic!("one invocation expected") };
assert_eq!(invocation.surface_key, surface.record_key());
assert!(commands_declared(&surface).contains(&invocation.command.as_str()));
let decl = surface.commands.iter().find(|decl| decl.id == invocation.command).unwrap();
assert_eq!(decl.captures.len(), 1);
assert_eq!(invocation.captured.len(), 1);
assert_eq!(invocation.captured[0].node, decl.captures[0]);
let [pending, completed] = &set.results[..] else { panic!("two results expected") };
assert!(pending.seq().get() < completed.seq().get(), "Pending precedes Completed in seq");
assert!(matches!(pending.outcome(), Outcome::Pending(_)));
let Outcome::Completed(done) = completed.outcome() else { panic!("not Completed") };
let Some(Effect::OpenExternal(external)) = &done.effect else { panic!("not OpenExternal") };
let CommandRef::Id(resume) = &external.resume else { panic!("resume is not a command id") };
assert!(commands_declared(&surface).contains(&resume.id.as_str()), "the resume command is declared");
for result in &set.results {
assert_eq!(result.invocation_id(), invocation.invocation_id);
}
}
#[test]
fn f03_places_an_absolute_target_over_an_image_from_its_catalog() {
let (set, surface) = single_surface(Fixture::F03InputTarget);
let root_children = box_children(&surface.root);
let Node::Image(image) = &root_children[0] else { panic!("the Image comes first") };
let [catalog] = &set.catalogs[..] else { panic!("one catalog expected") };
assert_eq!(catalog.catalog_id.as_str(), image.catalog);
assert!(catalog.assets.iter().any(|asset| asset.id == image.asset), "the catalog holds the asset");
let Node::Box(target) = &root_children[1] else { panic!("the target Box follows the Image") };
assert_eq!(target.style.position, Position::Absolute);
assert_ne!(target.style.inset.top, Dimension::Auto);
assert_ne!(target.style.inset.left, Dimension::Auto);
let Node::Text(label) = &target.children[0] else { panic!("not a Text") };
assert!(matches!(label.content, TextSource::Bound(_)), "the label is bound");
}
#[test]
fn f04_one_command_captures_all_four_inputs_and_clears_drafts() {
let (set, surface) = single_surface(Fixture::F04Form);
let [save] = &surface.commands[..] else { panic!("one command expected") };
let inputs: Vec<&str> = nodes(&set)
.into_iter()
.filter(|node| matches!(node, Node::Toggle(_) | Node::Slider(_) | Node::Select(_) | Node::TextInput(_)))
.map(|node| match node {
Node::Toggle(node) => node.common.id.as_str(),
Node::Slider(node) => node.common.id.as_str(),
Node::Select(node) => node.common.id.as_str(),
Node::TextInput(node) => node.common.id.as_str(),
_ => unreachable!(),
})
.collect();
let captures: Vec<&str> = save.captures.iter().map(NodeId::as_str).collect();
assert_eq!(captures, inputs);
let [invocation] = &set.invocations[..] else { panic!("one invocation expected") };
let carried: Vec<&str> = invocation.captured.iter().map(|input| input.node.as_str()).collect();
assert_eq!(carried, captures);
let [result] = &set.results[..] else { panic!("one result expected") };
assert!(matches!(result.outcome(), Outcome::Completed(done) if done.clear_drafts));
let kinds: Vec<&InputKind> = nodes(&set)
.into_iter()
.filter_map(|node| if let Node::TextInput(input) = node { Some(&input.input_kind) } else { None })
.collect();
assert_eq!(kinds, [&InputKind::Number]);
let options = nodes(&set).into_iter().find_map(|node| if let Node::Select(select) = node { Some(select) } else { None });
assert!(matches!(&options.unwrap().options, OptionList::Literal(literal) if literal.options.len() == 2));
}
#[test]
fn f05_is_a_modal_viewport_overlay_with_two_focusable_controls_and_a_declared_dismiss() {
let (set, surface) = single_surface(Fixture::F05ModalOverlay);
let all = nodes(&set);
let Some(Node::Overlay(overlay)) = all.iter().copied().find(|node| matches!(node, Node::Overlay(_))) else {
panic!("no Overlay")
};
assert_eq!(overlay.anchor, Anchor::Viewport);
assert!(overlay.modal);
let CommandRef::Id(dismiss) = &overlay.dismiss else { panic!("dismiss is not a command id") };
assert!(commands_declared(&surface).contains(&dismiss.id.as_str()));
let mut inside = Vec::new();
overlay.children.iter().for_each(|child| walk(child, &mut inside));
assert_eq!(inside.iter().filter(|node| matches!(node, Node::Button(_))).count(), 2);
}
#[test]
fn f06_scrolls_a_repeat_over_a_records_prefix() {
let (_, surface) = single_surface(Fixture::F06ScrollList);
let Node::Box(root) = &surface.root else { panic!("root is not a Box") };
assert_eq!(root.style.overflow, Overflow::Scroll);
let [Node::Repeat(items)] = &root.children[..] else { panic!("one Repeat expected") };
assert!(matches!(&items.collection, CollectionSource::Records(records) if !records.key_prefix.is_empty()));
assert_eq!(items.key_member, thing_testkit::build::path(&["Id"]));
}
#[test]
fn f07_plots_each_mark_over_a_bound_series() {
let (set, _) = single_surface(Fixture::F07Plot);
let marks: Vec<&PlotMark> = nodes(&set)
.into_iter()
.filter_map(|node| if let Node::Plot(plot) = node { Some(&plot.mark) } else { None })
.collect();
assert_eq!(marks, [&PlotMark::Line, &PlotMark::Bar, &PlotMark::Area]);
for node in nodes(&set) {
if let Node::Plot(plot) = node {
assert!(matches!(plot.series.source, StateSource::Record(_)));
}
}
}
#[test]
fn f08_embeds_a_fixed_size_leaf_among_siblings() {
let (_, surface) = single_surface(Fixture::F08EmbedViewport);
let children = box_children(&surface.root);
assert!(children.len() >= 3);
let embeds: Vec<&EmbedNode> = children.iter().filter_map(|node| if let Node::Embed(e) = node { Some(e) } else { None }).collect();
let [embed] = &embeds[..] else { panic!("one Embed expected") };
assert!(embed.width > 0.0 && embed.height > 0.0);
assert!(children.iter().any(|node| matches!(node, Node::Text(_))), "siblings around the Embed");
}
#[test]
fn f11_is_the_deepest_chain_the_bound_admits_and_one_more_level_is_refused() {
let (set, surface) = single_surface(Fixture::F11Deep);
let cache = Fixture::F11Deep.open();
let stored = cache.snapshot_envelopes();
assert_eq!(stored.len(), 1);
// The committed surface passes CultCache's own check and decodes to the built chain.
assert_eq!(check_payload_depth(&stored[0].payload), Ok(()));
assert_eq!(rmp_serde::to_vec(&surface).unwrap(), stored[0].payload);
let levels = {
let mut levels = 0;
let mut node = &surface.root;
while let Node::Box(boxed) = node {
levels += 1;
match boxed.children.first() {
Some(child) => node = child,
None => break,
}
}
levels
};
assert!(levels > 1, "a chain, not one Box");
assert_eq!(set.surfaces.len(), 1);
// One Box level deeper is refused by the check, naming depth 257, and by CultCache.
let refused = golden::read(&Fixture::dir(), Fixture::DEEP_REFUSED);
assert_eq!(refused, Fixture::deep_refused_payload());
assert_eq!(check_payload_depth(&refused), Err(PayloadTooDeep { depth: 257, limit: 256 }));
let mut cache = store::memory();
let envelope = CultCacheEnvelope {
key: surface.record_key(),
r#type: "gamecult.thing.surface".into(),
payload: refused,
stored_at: store::PINNED_CLOCK.into(),
schema_id: Some("gamecult.thing.surface.v1".into()),
};
let error = cache.put_raw_envelope(envelope).unwrap_err();
assert!(error.downcast_ref::<PayloadTooDeep>().is_some(), "{error:#}");
assert!(cache.get::<SurfaceDocument>(&surface.record_key()).unwrap().is_none());
}
#[test]
fn f12_holds_each_text_edge_case_as_its_own_node() {
let (set, _) = single_surface(Fixture::F12TextEdge);
let texts: Vec<(&str, &str)> = nodes(&set)
.into_iter()
.filter_map(|node| match node {
Node::Text(text) => match &text.content {
TextSource::Literal(literal) => Some((text.common.id.as_str(), literal.value.as_str())),
_ => None,
},
_ => None,
})
.collect();
let ids: Vec<&str> = texts.iter().map(|(id, _)| *id).collect();
assert_eq!(ids, ["bidi", "cjk", "combining", "emoji-zwj", "long-wrap"]);
let content = |id: &str| texts.iter().find(|(name, _)| *name == id).unwrap().1;
assert!(content("bidi").chars().any(|c| ('\u{590}'..='\u{6ff}').contains(&c)) && content("bidi").is_ascii() == false);
assert!(content("bidi").contains("Hello"));
assert!(content("cjk").chars().any(|c| ('\u{4e00}'..='\u{9fff}').contains(&c)));
assert!(content("combining").chars().any(|c| ('\u{300}'..='\u{36f}').contains(&c)));
assert!(content("emoji-zwj").contains('\u{200d}'));
assert!(content("long-wrap").len() > 400);
}

View file

@ -0,0 +1,86 @@
//! The bless door compares and never writes unless `THING_BLESS=1`. These tests assume it is
//! unset; the bless job runs only the fixtures test.
use std::panic::catch_unwind;
use std::path::PathBuf;
use thing_testkit::golden;
fn scratch(name: &str) -> PathBuf {
let dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(format!("golden-{name}"));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn a_mismatch_panics_naming_the_file_and_leaves_it_unchanged() {
let dir = scratch("mismatch");
std::fs::write(dir.join("a.bin"), b"committed").unwrap();
assert_eq!(golden::check(&dir, "a.bin", b"committed"), b"committed");
let panic = catch_unwind(|| golden::check(&dir, "a.bin", b"different")).unwrap_err();
let message = panic.downcast_ref::<String>().cloned().unwrap_or_default();
assert!(message.contains("a.bin"), "the panic names the file: {message}");
assert_eq!(std::fs::read(dir.join("a.bin")).unwrap(), b"committed");
}
#[test]
fn a_missing_file_is_a_failure_not_a_write() {
let dir = scratch("missing");
assert!(catch_unwind(|| golden::check(&dir, "absent.bin", b"x")).is_err());
assert!(catch_unwind(|| golden::read(&dir, "absent.bin")).is_err());
assert!(!dir.join("absent.bin").exists());
}
#[test]
fn the_text_beside_the_binary_is_compared_too() {
let dir = scratch("text");
std::fs::write(dir.join("s.bin"), b"bytes").unwrap();
std::fs::write(dir.join("s.txt"), "text").unwrap();
assert_eq!(golden::check_with_text(&dir, "s", b"bytes", "text"), b"bytes");
let panic = catch_unwind(|| golden::check_with_text(&dir, "s", b"bytes", "other")).unwrap_err();
let message = panic.downcast_ref::<String>().cloned().unwrap_or_default();
assert!(message.contains("s.txt"), "the panic names the text file: {message}");
assert_eq!(std::fs::read(dir.join("s.txt")).unwrap(), b"text");
assert!(catch_unwind(|| golden::check_with_text(&dir, "s", b"changed", "text")).is_err());
assert_eq!(std::fs::read(dir.join("s.bin")).unwrap(), b"bytes");
}
#[test]
fn read_returns_the_committed_bytes() {
let dir = scratch("read");
std::fs::write(dir.join("r.bin"), b"abc").unwrap();
assert_eq!(golden::read(&dir, "r.bin"), b"abc");
}
/// Re-runs this binary with THING_BLESS=1 so the writer is observed without touching this
/// process's environment.
#[test]
fn blessing_writes_the_file_and_the_text() {
let dir = scratch("bless");
let status = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "bless_child", "--test-threads=1"])
.env("THING_BLESS", "1")
.env("THING_BLESS_CHILD_DIR", &dir)
.status()
.unwrap();
assert!(status.success());
assert_eq!(std::fs::read(dir.join("b.bin")).unwrap(), b"blessed");
assert_eq!(std::fs::read(dir.join("t.bin")).unwrap(), b"tb");
assert_eq!(std::fs::read(dir.join("t.txt")).unwrap(), b"tt");
}
/// The child half of the test above; does nothing in a normal run.
#[test]
fn bless_child() {
if let Ok(dir) = std::env::var("THING_BLESS_CHILD_DIR") {
let dir = PathBuf::from(dir);
golden::check(&dir, "b.bin", b"blessed");
golden::check_with_text(&dir, "t", b"tb", "tt");
}
}

View file

@ -0,0 +1,305 @@
//! MemState as core sees it: through `StatePort`, with its own put and delete as the only
//! writers.
use std::path::PathBuf;
use thing_contract::*;
use thing_core::port::{Address, Change, Entry, Interest, Lookup, Prefix, Record, StatePort, SubscriptionId};
use thing_testkit::build::*;
use thing_testkit::golden;
use thing_testkit::mem_state::{Call, MemState};
const SURFACE: &str = "gamecult.thing.surface.v1";
const COMPOSITION: &str = "gamecult.thing.composition.v1";
const RESULT: &str = "gamecult.thing.command_result.v1";
const CATALOG: &str = "gamecult.thing.asset_catalog.v1";
// A value that must never appear in a refusal; node-unknown-arm.bin carries it.
const CANARY: &str = "CANARY-7f3a91c2";
fn provider(name: &str) -> ProviderId {
ProviderId::new(name)
}
fn address(provider_name: &str, schema: &str, key: &str) -> Address {
Address { provider: provider(provider_name), schema: SchemaId::new(schema), key: RecordKey::new(key) }
}
fn prefix(provider_name: &str, schema: &str, key_prefix: &str) -> Prefix {
Prefix { provider: provider(provider_name), schema: SchemaId::new(schema), key_prefix: key_prefix.into() }
}
fn surface(provider_name: &str, label: &str) -> SurfaceDocument {
SurfaceDocument {
provider_id: provider(provider_name),
label: seg(label),
version: ver(1),
title: label.into(),
root: boxed("root", vec![]),
commands: vec![],
}
}
fn composition(publisher: &str, name: &str) -> CompositionDocument {
CompositionDocument {
publisher: publisher.into(),
name: seg(name),
version: ver(1),
params: vec![],
body: boxed("body", vec![]),
}
}
fn catalog(provider_name: &str, id: &str) -> AssetCatalog {
AssetCatalog { provider_id: provider(provider_name), catalog_id: seg(id), version: ver(1), assets: vec![] }
}
fn surface_at(provider_name: &str, value: &SurfaceDocument) -> Address {
address(provider_name, SURFACE, &value.record_key())
}
fn unknown_arm() -> Vec<u8> {
let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../thing-contract/tests/goldens");
golden::read(&dir, "node-unknown-arm.bin")
}
#[test]
fn port_is_object_safe() {
let one = surface("provider.a", "one");
let mut state = MemState::new();
state.put(&provider("provider.a"), &one);
let port: &mut dyn StatePort = &mut state;
let id = port.subscribe(Interest::Record(surface_at("provider.a", &one)));
assert!(matches!(port.read(&surface_at("provider.a", &one)), Lookup::Present(_)));
assert_eq!(port.list(&prefix("provider.a", SURFACE, "thing:")).len(), 1);
port.unsubscribe(id);
assert!(port.drain().is_empty());
let boxed: Box<dyn StatePort> = Box::new(MemState::new());
assert_eq!(boxed.read(&address("provider.a", SURFACE, "k")), Lookup::Absent);
}
#[test]
fn a_refusal_is_not_absence() {
let main = surface("provider.a", "main");
let at = surface_at("provider.a", &main);
assert_eq!(at.key.as_str(), "thing:surface:provider.a.main");
let mut state = MemState::new();
state.subscribe(Interest::Prefix(prefix("provider.a", SURFACE, "thing:")));
state.put_raw(at.clone(), unknown_arm());
let drained = state.drain();
assert_eq!(drained.len(), 1, "one change: {drained:?}");
let Change::Refused(refusal) = &drained[0] else { panic!("not a refusal: {drained:?}") };
assert_eq!(refusal.address, at);
assert_eq!(refusal.kind, SchemaId::new(SURFACE));
assert!(refusal.detail.contains(at.key.as_str()), "the detail names the key: {}", refusal.detail);
assert!(!refusal.detail.contains(CANARY), "the detail echoed a value: {}", refusal.detail);
assert_eq!(state.read(&at), Lookup::Refused(refusal.clone()));
assert_eq!(state.list(&prefix("provider.a", SURFACE, "thing:")), vec![Lookup::Refused(refusal.clone())]);
// A valid record replaces the refusal; a refusal over a valid record leaves the address
// refused, not the older record.
state.put(&provider("provider.a"), &main);
assert!(matches!(state.read(&at), Lookup::Present(_)));
state.put_raw(at.clone(), unknown_arm());
assert!(matches!(state.read(&at), Lookup::Refused(_)));
assert_eq!(state.list(&prefix("provider.a", SURFACE, "thing:")).len(), 1);
state.drain();
// Deleting a refusal is a change; deleting nothing is not.
state.delete(&at);
assert_eq!(state.read(&at), Lookup::Absent);
assert_eq!(state.drain(), vec![Change::Delete(at.clone())]);
state.delete(&at);
assert!(state.drain().is_empty());
}
#[test]
fn changes_drain_in_mutation_order_for_live_interests() {
let provider_a = provider("provider.a");
let one = surface("provider.a", "one");
let two = surface("provider.a", "two");
let panel = composition("provider.a", "panel");
let other = composition("provider.a", "other");
let icons = catalog("provider.a", "icons");
let one_at = surface_at("provider.a", &one);
let panel_at = address("provider.a", COMPOSITION, &panel.record_key());
let mut state = MemState::new();
let ids: Vec<SubscriptionId> = vec![
state.subscribe(Interest::Record(one_at.clone())),
state.subscribe(Interest::Record(panel_at.clone())),
state.subscribe(Interest::Prefix(prefix("provider.a", SURFACE, "thing:"))),
];
state.put(&provider_a, &one); // matches two interests and drains once
state.put(&provider_a, &panel);
state.put(&provider_a, &icons); // another schema under the same provider
state.put(&provider_a, &other); // a composition nobody asked for
// The same key and schema under another provider.
state.put_raw(address("provider.b", SURFACE, &two.record_key()), rmp_serde::to_vec(&two).unwrap());
state.put(&provider_a, &two);
state.delete(&one_at);
let entry = |address: Address, record: Record| Change::Upsert(Entry { address, record });
assert_eq!(
state.drain(),
vec![
entry(one_at.clone(), Record::Surface(one.clone())),
entry(panel_at, Record::Composition(panel)),
entry(surface_at("provider.a", &two), Record::Surface(two.clone())),
Change::Delete(one_at),
]
);
assert!(state.drain().is_empty(), "each change drains once");
for id in ids {
state.unsubscribe(id);
}
state.put(&provider_a, &one);
assert!(state.drain().is_empty());
}
#[test]
fn without_a_live_interest_nothing_queues() {
let mut state = MemState::new();
state.put_raw(address("provider.a", SURFACE, "thing:surface:provider.a.main"), unknown_arm());
state.put(&provider("provider.a"), &surface("provider.a", "one"));
assert!(state.drain().is_empty());
}
#[test]
fn each_kind_reads_back_as_its_own_arm() {
let provider_a = provider("provider.a");
let mut state = MemState::new();
let first = surface("provider.a", "b");
let invocation = invocation();
let result = CommandResult::pending(&invocation, seq(1), "working");
let panel = composition("provider.a", "panel");
let icons = catalog("provider.a", "icons");
state.put(&provider_a, &first);
state.put(&provider_a, &panel);
state.put(&provider_a, &result);
state.put(&provider_a, &icons);
let present = |at: Address, record: Record| Lookup::Present(Entry { address: at, record });
let first_at = surface_at("provider.a", &first);
assert_eq!(state.read(&first_at), present(first_at.clone(), Record::Surface(first.clone())));
let panel_at = address("provider.a", COMPOSITION, &panel.record_key());
assert_eq!(state.read(&panel_at), present(panel_at.clone(), Record::Composition(panel)));
let result_at = address("provider.a", RESULT, &result.record_key());
assert_eq!(state.read(&result_at), present(result_at.clone(), Record::Result(result)));
let icons_at = address("provider.a", CATALOG, &icons.record_key());
assert_eq!(state.read(&icons_at), present(icons_at.clone(), Record::Catalog(icons)));
// A newer record replaces the older; an absent key, another provider and another schema read Absent.
let mut newer = first.clone();
newer.title = "newer".into();
state.put(&provider_a, &newer);
assert_eq!(state.read(&first_at), present(first_at.clone(), Record::Surface(newer)));
assert_eq!(state.read(&address("provider.a", SURFACE, "missing")), Lookup::Absent);
assert_eq!(state.read(&address("provider.b", SURFACE, first_at.key.as_str())), Lookup::Absent);
assert_eq!(state.read(&address("provider.a", COMPOSITION, first_at.key.as_str())), Lookup::Absent);
assert_eq!(state.read(&address("provider.a", "gamecult.thing.nowhere.v1", "k")), Lookup::Absent);
// A list holds the prefix's records in key order and no others.
let a = surface("provider.a", "a");
let c = surface("provider.a", "c");
state.put(&provider_a, &c);
state.put(&provider_a, &a);
let keys: Vec<String> = state
.list(&prefix("provider.a", SURFACE, "thing:surface:provider.a."))
.into_iter()
.map(|lookup| match lookup {
Lookup::Present(entry) => entry.address.key.as_str().to_string(),
other => panic!("{other:?}"),
})
.collect();
assert_eq!(keys, ["thing:surface:provider.a.a", "thing:surface:provider.a.b", "thing:surface:provider.a.c"]);
assert_eq!(state.list(&prefix("provider.a", SURFACE, "thing:surface:provider.a.b")).len(), 1);
assert!(state.list(&prefix("provider.b", SURFACE, "thing:")).is_empty());
}
#[test]
fn every_call_is_logged_in_order() {
let at = address("provider.a", SURFACE, "k");
let under = prefix("provider.a", SURFACE, "p");
let mut state = MemState::new();
state.read(&at);
let id = state.subscribe(Interest::Prefix(under.clone()));
state.list(&under);
state.drain();
state.unsubscribe(id);
assert_eq!(
state.calls(),
vec![
Call::Read(at.clone()),
Call::Subscribe(Interest::Prefix(under.clone())),
Call::List(under),
Call::Drain,
Call::Unsubscribe(id),
]
);
let second = state.subscribe(Interest::Record(at));
assert_ne!(second, id, "a subscription id is never reused");
}
#[test]
fn unsubscribing_ends_only_that_interest() {
let provider_a = provider("provider.a");
let panel = composition("provider.a", "panel");
let one = surface("provider.a", "one");
let panel_at = address("provider.a", COMPOSITION, &panel.record_key());
let mut state = MemState::new();
let by_record = state.subscribe(Interest::Record(panel_at.clone()));
let by_prefix = state.subscribe(Interest::Prefix(prefix("provider.a", SURFACE, "thing:")));
state.unsubscribe(by_prefix);
state.put(&provider_a, &one);
state.put(&provider_a, &panel);
let drained = state.drain();
assert_eq!(drained.len(), 1, "only the composition interest is live: {drained:?}");
assert!(matches!(&drained[0], Change::Upsert(entry) if entry.address == panel_at));
state.unsubscribe(by_record);
state.put(&provider_a, &panel);
assert!(state.drain().is_empty());
}
#[test]
fn unsubscribing_keeps_changes_already_queued() {
let one = surface("provider.a", "one");
let mut state = MemState::new();
let id = state.subscribe(Interest::Record(surface_at("provider.a", &one)));
state.put(&provider("provider.a"), &one);
state.unsubscribe(id);
assert_eq!(state.drain().len(), 1, "a change queued while the interest was live is still drained");
}
#[test]
fn a_list_mixes_refused_and_present_in_key_order() {
let a = surface("provider.a", "a");
let c = surface("provider.a", "c");
let b_at = address("provider.a", SURFACE, "thing:surface:provider.a.b");
let mut state = MemState::new();
state.put(&provider("provider.a"), &c);
state.put_raw(b_at.clone(), unknown_arm());
state.put(&provider("provider.a"), &a);
let kinds: Vec<(&str, String)> = state
.list(&prefix("provider.a", SURFACE, "thing:"))
.into_iter()
.map(|lookup| match lookup {
Lookup::Present(entry) => ("present", entry.address.key.as_str().to_string()),
Lookup::Refused(refusal) => ("refused", refusal.address.key.as_str().to_string()),
Lookup::Absent => panic!("a list holds no absence"),
})
.collect();
assert_eq!(
kinds,
[
("present", "thing:surface:provider.a.a".to_string()),
("refused", b_at.key.as_str().to_string()),
("present", "thing:surface:provider.a.c".to_string()),
]
);
}

View file

@ -0,0 +1,24 @@
//! Writing a fixture leaves nothing behind. This is the only test in its binary, so no other
//! thread creates scratch files while it counts.
use thing_testkit::fixture::Fixture;
fn scratch_entries() -> Vec<String> {
let prefix = "thing-testkit-";
let mut names: Vec<String> = std::fs::read_dir(std::env::temp_dir())
.unwrap()
.filter_map(|entry| entry.unwrap().file_name().into_string().ok())
.filter(|name| name.starts_with(prefix) && name.contains(&format!("-{}-", std::process::id())))
.collect();
names.sort();
names
}
#[test]
fn writing_a_fixture_leaves_no_scratch_file_or_lock_behind() {
let before = scratch_entries();
for fixture in Fixture::ALL {
fixture.write();
}
assert_eq!(scratch_entries(), before);
}

View file

@ -0,0 +1,223 @@
//! Provider state through MemState: decoded by name from a Rust-written store, refused from a
//! store that published no member rows, and held one record per key as CultCache holds them.
use cultcache_rs::DatabaseEntry;
use thing_contract::{ProviderId, SchemaId};
use thing_state::StateDecodeError;
use thing_core::port::{Address, Change, Entry, Interest, Lookup, Prefix, Record, StatePort, StateValue};
use thing_testkit::fixture::Fixture;
use thing_testkit::mem_state::MemState;
use thing_testkit::state::*;
use StateValue::*;
const SWARM_SCHEMA: &str = "gamecult.thing.test.swarm.v1";
const NOWHERE: &str = "gamecult.thing.test.nowhere.v1";
const PROVIDER: &str = "provider.swarm";
fn at(schema: &str, key: &str) -> Address {
address(PROVIDER, schema, key)
}
fn prefix(schema: &str, key_prefix: &str) -> Prefix {
Prefix { provider: ProviderId::new(PROVIDER), schema: SchemaId::new(schema), key_prefix: key_prefix.into() }
}
fn loaded(file: &str) -> MemState {
let mut state = MemState::new();
state.load_store(&ProviderId::new(PROVIDER), &Fixture::dir().join(file));
state
}
fn swarm_value(id: &str, name: &str, load: f64) -> StateValue {
Record(vec![("Id".into(), Text(id.into())), ("Name".into(), Text(name.into())), ("Load".into(), Float(load))])
}
#[test]
fn the_committed_stores_are_what_the_crate_writes() {
assert!(!write_swarm_store().is_empty());
assert!(!write_swarm_store_members_empty().is_empty());
}
#[test]
fn a_rust_written_store_reads_by_the_names_it_published() {
let state = loaded(SWARM_STORE);
let found = state.read(&at(SWARM_SCHEMA, "summary"));
let Lookup::Present(entry) = found else { panic!("{found:?}") };
assert_eq!(entry.address, at(SWARM_SCHEMA, "summary"));
assert_eq!(
entry.record,
Record::State { schema: SchemaId::new(SWARM_SCHEMA), value: swarm_value("summary", "Swarm", 0.42) }
);
let Record::State { value, .. } = entry.record else { unreachable!() };
assert_eq!(value.member("Load"), Some(&Float(0.42)));
assert_eq!(state.read(&at(SWARM_SCHEMA, "unused")), Lookup::Absent);
let listed = state.list(&prefix(SWARM_SCHEMA, "mind-"));
let keys: Vec<_> = listed
.iter()
.map(|lookup| match lookup {
Lookup::Present(entry) => entry.address.key.as_str().to_string(),
other => panic!("{other:?}"),
})
.collect();
assert_eq!(keys, ["mind-1", "mind-2", "mind-3"]);
}
#[test]
fn a_store_with_no_member_rows_is_refused_never_read_positionally() {
let state = loaded(SWARM_STORE_MEMBERS_EMPTY);
for key in ["summary", "mind-1", "mind-2", "mind-3"] {
let found = state.read(&at(SWARM_SCHEMA, key));
let Lookup::Refused(refusal) = found else { panic!("{key}: {found:?}") };
assert_eq!(refusal.kind, SchemaId::new(SWARM_SCHEMA));
assert!(refusal.detail.contains(SWARM_SCHEMA), "{}", refusal.detail);
assert!(refusal.detail.contains(&StateDecodeError::NoMembers.to_string()), "{}", refusal.detail);
}
let listed = state.list(&prefix(SWARM_SCHEMA, "mind-"));
assert_eq!(listed.len(), 3);
assert!(listed.iter().all(|lookup| matches!(lookup, Lookup::Refused(_))), "{listed:?}");
}
#[test]
fn a_script_and_a_store_hold_the_same_records() {
let mut scripted = MemState::new();
script(Fixture::F01SwarmDashboard, &mut scripted);
let stored = loaded(SWARM_STORE);
for key in ["summary", "mind-1", "mind-2", "mind-3"] {
assert_eq!(scripted.read(&at(SWARM_SCHEMA, key)), stored.read(&at(SWARM_SCHEMA, key)), "{key}");
}
}
#[test]
fn another_schema_at_the_key_answers_present_under_its_own_schema() {
let mut state = MemState::new();
script(Fixture::F10Hostile, &mut state);
let asked = address("provider.hostile", NOWHERE, "row-1");
let found = state.read(&asked);
let Lookup::Present(entry) = found else { panic!("{found:?}") };
assert_eq!(entry.address, asked);
let Record::State { schema, .. } = entry.record else { panic!("not state") };
assert_eq!(schema, SchemaId::new(SWARM_SCHEMA));
assert_eq!(state.read(&address("provider.hostile", NOWHERE, "row-2")), Lookup::Absent);
// A list names only the records of the schema asked for.
let none = state.list(&Prefix {
provider: ProviderId::new("provider.hostile"),
schema: SchemaId::new(NOWHERE),
key_prefix: String::new(),
});
assert!(none.is_empty());
}
#[test]
fn every_state_script_fills_the_provider_its_fixture_binds() {
let mut feed = MemState::new();
script(Fixture::F06ScrollList, &mut feed);
let items = feed.list(&Prefix {
provider: ProviderId::new("provider.feed"),
schema: SchemaId::new("gamecult.thing.test.item.v1"),
key_prefix: "item-".into(),
});
assert_eq!(items.len(), 1000);
let Lookup::Present(first) = &items[0] else { panic!() };
assert_eq!(first.address.key.as_str(), "item-0000");
for (fixture, provider, schema, key, member) in [
(Fixture::F03InputTarget, "provider.muninn", "target", "cursor", "Label"),
(Fixture::F04Form, "provider.settings", "settings", "current", "Volume"),
(Fixture::F07Plot, "provider.market", "series", "prices", "Values"),
] {
let mut state = MemState::new();
script(fixture, &mut state);
let found = state.read(&address(provider, &format!("gamecult.thing.test.{schema}.v1"), key));
let Lookup::Present(Entry { record: Record::State { value, .. }, .. }) = found else {
panic!("{schema}: {found:?}")
};
assert!(value.member(member).is_some(), "{schema}.{member}");
}
}
#[test]
fn a_refused_put_replaces_an_older_good_record() {
let mut state = MemState::new();
let key = at(SWARM_SCHEMA, "summary");
state.subscribe(Interest::Record(key.clone()));
let swarm = Swarm { id: "summary".into(), name: "Swarm".into(), load: 0.5 };
state.put_state(&ProviderId::new(PROVIDER), "summary", &swarm);
assert!(matches!(state.read(&key), Lookup::Present(_)));
state.put_state_raw(key.clone(), vec![0xc1], &Swarm::schema_members());
let Lookup::Refused(refusal) = state.read(&key) else { panic!("not refused") };
assert_eq!(refusal.address, key);
// Refused whichever schema is asked at that key.
assert!(matches!(state.read(&at(NOWHERE, "summary")), Lookup::Refused(_)));
let changes = state.drain();
assert!(matches!(changes.as_slice(), [Change::Upsert(_), Change::Refused(_)]), "{changes:?}");
// A good record replaces the refusal.
state.put_state(&ProviderId::new(PROVIDER), "summary", &swarm);
assert!(matches!(state.read(&key), Lookup::Present(_)));
}
#[test]
fn delete_queues_only_under_a_matching_interest_and_only_for_what_was_held() {
let mut state = MemState::new();
let key = at(SWARM_SCHEMA, "summary");
state.subscribe(Interest::Prefix(prefix(SWARM_SCHEMA, "sum")));
let swarm = Swarm { id: "s".into(), name: "n".into(), load: 0.0 };
state.put_state(&ProviderId::new(PROVIDER), "summary", &swarm);
state.put_state(&ProviderId::new(PROVIDER), "mind-1", &swarm);
state.delete(&at(NOWHERE, "summary")); // another schema's address: nothing held there
assert!(matches!(state.read(&key), Lookup::Present(_)));
state.delete(&key);
state.delete(&key); // already gone
state.delete(&at(SWARM_SCHEMA, "mind-1")); // held, but no interest
assert_eq!(state.read(&key), Lookup::Absent);
assert_eq!(state.read(&at(SWARM_SCHEMA, "mind-1")), Lookup::Absent);
let changes = state.drain();
assert!(
matches!(changes.as_slice(), [Change::Upsert(_), Change::Delete(deleted)] if *deleted == key),
"{changes:?}"
);
}
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
#[cultcache(type = "gamecult.thing.test.other", schema = "gamecult.thing.test.other.v1")]
struct TypeIsNotTheSchemaId {
#[cultcache(key = 0)]
id: String,
}
#[test]
#[should_panic(expected = "entry type equal to its schema id")]
fn put_state_refuses_a_type_that_is_not_its_schema_id() {
MemState::new().put_state(&ProviderId::new(PROVIDER), "k", &TypeIsNotTheSchemaId { id: "x".into() });
}
#[test]
#[should_panic(expected = "is a contract kind")]
fn put_state_raw_refuses_a_contract_schema() {
let mut state = MemState::new();
state.put_state_raw(at("gamecult.thing.surface.v1", "k"), vec![0x90], &Swarm::schema_members());
}
#[test]
fn load_store_names_a_record_by_its_schema_id_when_it_has_one() {
// The schema id the store carries is the record's schema, whatever its entry type is called.
let dir = std::env::temp_dir().join(format!("thing-state-alias-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("alias.cc");
let bytes = thing_testkit::store::bytes(|cache| {
cache.register_entry_type::<Swarm>().unwrap();
let swarm = Swarm { id: "a".into(), name: "n".into(), load: 1.0 };
let (mut envelope, _) = cache.prepare_entry("k", &swarm).unwrap();
envelope.stored_at = thing_testkit::store::PINNED_CLOCK.into();
envelope.schema_id = Some("gamecult.thing.test.alias.v1".into());
cache.put_envelope::<Swarm>(envelope).unwrap();
});
std::fs::write(&path, bytes).unwrap();
let mut state = MemState::new();
state.load_store(&ProviderId::new(PROVIDER), &path);
let _ = std::fs::remove_dir_all(&dir);
// No member rows are published under the alias, so the record is refused under it; read
// by its entry type it would have decoded.
let found = state.read(&at("gamecult.thing.test.alias.v1", "k"));
let Lookup::Refused(refusal) = found else { panic!("{found:?}") };
assert_eq!(refusal.kind, SchemaId::new("gamecult.thing.test.alias.v1"));
}

View file

@ -0,0 +1,201 @@
# Swarm dashboard: contract state, sources, first cut
Serves Eureka's ruling `swarm-dashboard-first-thing2-surface` (not readable from
the libby mind; cited by the id in the claiming follow-up
`libby-body:follow_up:chat-s354-359`). Read-only pass by the `libby` Self run
`libby:run:mind-20261031T061423908Z`, 2026-10-31. Nothing was built or deployed.
Claims below were probed on 2026-10-31 unless marked **unverified**.
The question the dashboard answers for a stranger: **is anyone working, and on what.**
## 1. Where Thing 2's surface contract stands
Probed against the forge `GameCult/Thing` (main `e119e76`, 2026-10-22) and its
`hands/thing2-*` branches. The source of truth for cut status is the `thing2`
campaign in the Eureka mind, which this pass cannot read; the prose map
(`docs/thing2-map.md`, last edited 2026-10-12) is the evidence used.
| Piece | State |
| --- | --- |
| Contract, Rust (`crates/thing-contract`) | On main. 13-arm closed `Node` union, `SurfaceDocument`, `CompositionDocument`, `CommandDecl/Invocation/Result`, `AssetCatalog`; byte goldens under `tests/goldens/`. |
| Contract, C# and TypeScript | Not on main. Branches `hands/thing2-contract-cs` (`3dadfc6`, 2026-10-14) and `hands/thing2-contract-ts` (`aeede04`, 2026-10-12). The map lists the cross-runtime store check and publication as waiting. |
| Core (resolution, `thing.std` compositions, binding via the CultMesh port, Taffy layout, command dispatch) | Not built. No crate exists. Decoding Verse surfaces waits on `cultlib-gaps:follow_up:decode-stack-safety`. |
| TUI backend | Not built. Planned first backend. |
| Web backend and shell | Not built. |
| Discovery/advertisement | Not a Thing kind (`thing2:ruling:advertisement-owner`); read through a core port; today's `gamecult.eve.provider_advertisement.v1` is unchanged. |
`README.md` says the same: the layout solver, text, accessibility tree, render
commands and backends "are not built yet". **Nothing can render a Thing 2
surface today.** The only live renderers are Thing 1's (browser oracle, Ghostlight's vendored lowering,
the Nightwing browser reference), and Eve dashboards are quarantined (`gamecult.md`: no new Eve surfaces).
### What a provider must publish to render
From `docs/thing2-map.md` "The consumer contract" and `crates/thing-contract/src`:
1. A `SurfaceDocument` (`gamecult.thing.surface.v1`, key `thing:surface:<providerId>.<label>`,
`version` bumped only on structure change). Closed nodes: `Box, Text, Image, Button, Toggle,
Slider, TextInput, Select, Repeat, Overlay, Plot, Embed, Use`. A swarm board is `Box` + `Text` +
`Repeat` (one row per instance) + `Use` of `thing.std` compositions (`card`, `metric`, `key-value`).
2. The **bound state records** the document points at, under the provider's own schema and key. A
`Bind` is `{provider?, schema, key, member path, format?}` plus `Item` inside a `Repeat`. A
collection binds to `{provider, schema, key_prefix}` or a list member of one record. No
expressions, no derived values: **the state's owner publishes derived values** (map rationale,
P5). So the dashboard's "working / idle" must be a published field, not computed in the surface.
3. Discovery: the provider is found through the existing advertisement, not a Thing record.
4. Commands only if the surface acts. A read-only board declares none.
A provider needs no layout or renderer code. It needs the contract package in its language
(Rust is the only one on main) and typed CultMesh state.
## 2. Sources (all typed state)
### 2a. Run documents, eight minds
Each mind is its own Huginn daemon (`HEARTBEAT_PERSONAS` in `/etc/gamecult/heartbeat/heartbeat.env`):
eureka 17872, libby 17873, heimdall 17874, kiko 17875, aqua 17876, weksa 17877, nibu 17878,
void 17879, all `rudp://10.77.0.1:<port>`. Probed: from this Self run,
`EUREKA_INSTANCE=<name> HUGINN_ENDPOINT=<endpoint> huginn query '{"schemas":["epiphany.pipeline.run.v2"],"limit":200}'`
answers on all eight, read-only, with caller `client unknown` (no per-client read identity yet).
Counts that day: eureka 68, libby 78, heimdall 94, kiko 70, aqua 81, weksa 74, nibu 71, void 87.
`epiphany.pipeline.run.v2` (`huginn schema run`): `instance, label, operated_by (Operator|Mind),
turn (PersonaTurn|SelfRun), host, started_on (a date), budget_usd, claims [PipelineRef], campaigns`.
What the dashboard can and cannot take from it:
- **Open/closed is not on the Run.** It is derived: a Run is closed when a `Resolution` with
`subject` = the run is in force (`huginn query` prints `InForce` or `Resolved:<outcome>`).
Resolution key `<instance>:resolution:run.<label>.n<seq>`. `huginn history <runId>` reads it.
- **Start time is a date.** The label `mind-YYYYMMDDTHHMMSSmmmZ` encodes the start to the
millisecond, but that is a convention in a string. The admission header (`huginn view`) carries
`admitted <timestamp>`, and the Resolution's header gives the end. Both are header facts, not
document fields. A dashboard needing start and end times wants them as typed fields.
- **"Outcome" is nearly empty.** Of 78 libby runs, 77 resolved `Recorded` and one is in force.
The meaning lives in free text: `reason "answered 1"` (55), `"answered 2"` (5), `"the connector
refused the credential lease: UnknownCaller"` (3), `"unit not active"`, `"failed after 0
answered..."`, plus rationales `The Persona unit's start ended.` (61) and `The Self run's carrier
closed the run its claude left open.` (11). Two Self-run resolutions carry the run's whole result
message inside `reason` (long prose, operator-facing detail). A public board
must **never project `reason` or `rationale`**.
- **"On what" is only on Self runs.** `claims` holds the follow-up or other document the run took;
a `PersonaTurn` has no claims (its work is the chat room). The claimed `follow_up.item` is the
operator's chat-relayed brief, free text, sometimes private. The typed handle (claim id, campaign
slug, the claimed document's `repo`) is safe; the `item` is not.
- **An open Run can be a dead Run.** Eleven libby Self runs were closed with "carrier closed the
run its claude left open", so for some interval an in-force Run belonged to nobody. "Open" is
"admitted and not yet resolved", not "a process is working".
- **Dollar fields:** `budget_usd` is on every Run. Do not bind it.
Snapshot at 06:16 UTC: two Self runs in force, `libby:run:mind-20261031T061423908Z` (this one) and
`void:run:mind-20261031T061543899Z` (claims `void-body:follow_up:chat-s335-340`); no Persona run
in force in any of the eight.
### 2b. Heartbeat state and poll trace
Source: `Huginn/crates/mind-body/src/heartbeat.rs`. `mind-heartbeat` is one Idunn-managed unit, sole
writer of `heartbeat.cc` (a single-file CultCache store under the unit's state directory). Two kinds:
- `eureka.heartbeat.initiative.v1`, key = instance slug: `initiative_usd, as_of, urgency, urgency_at,
last_burned_run, filled_events, classified_seq, launched_run, launch_spend_usd,
launch_spend_known, completions_through, launch_window`.
- `eureka.heartbeat.poll_trace.v1`, key = zero-padded unix ms, written only for polls that changed
something: `at, instances [InstanceTrace], launches [run label], burns [BurnTrace], classifier`.
`InstanceTrace`: `instance, initiative_usd, rate_usd_per_h, urgency, urgency_age_s, busy,
released, crossing_at, waited_s, idle_s, filled_by, fill_reason, note`.
Usable without dollars: `busy` (an in-force Persona run, from the mind), `released`, `crossing_at`,
`waited_s`, `idle_s`, `filled_by`/`fill_reason` (`tag` or `name`), `note`, `launches`, `urgency`,
`classifier`. These say **why nobody is working** (waiting for initiative, held by the envelope).
Dollar fields to leave alone: `initiative_usd`, `rate_usd_per_h`, `launch_spend_usd`,
`spend_usd`, and in the Initiative record the same names. The metering teardown removes them, and
`initiative_usd` is the unit initiative itself is denominated in, so the heartbeat's own model will
change under whatever binds this.
Gaps:
- **Not verified live.** `heartbeat.cc` is not readable from this Self run's account, and no
`/var/lib/gamecult` path for it was visible. The shape above is from source and
`eureka-body-map.md:534-540`, not from a read of the file.
- **No wire.** The heartbeat writes a file; it does not serve one. A reader opening a single-file
store while the heartbeat rewrites it has no stated safety (`FileStore::open` pulls the whole file
per call). A dashboard source must be published state, not a second process reading the file.
`mind-heartbeat timeline` prints the latest poll for a human.
- The trace is written only when a poll "changed something", so its newest line can be old while
the system is healthy. Staleness must come from the heartbeat's own published liveness, which
does not exist as a field.
### 2c. Connector usage readout
Source: `ModelConnector/schemas/usage_readout.json`, `crates/model-connector/src/readout.rs`.
`gamecult.model.usage_readout.v1`: `{schema_id, at_unix_ms, plan_quota: [{window, status,
utilization_permille (nullable), resets_at_unix_ms, observed_at_unix_ms}]}`. Whole-plan windows, no
per-caller field, **no dollars**: the safe source for "how much capacity is left".
Gaps: it is a connector operation (`usage_readout` on `gamecult.model.connector`), reached at the
heartbeat's `MIND_CONNECTOR_ENDPOINT` (`tcp://127.0.0.1:4110`), a loopback port with a per-caller
credential. Three libby Self runs were already refused with `UnknownCaller` on a lease, so a new
caller needs registration before it can ask. It is a request/answer, not a document in a store. A
dashboard needs a publisher that polls it and republishes it as a CultMesh record. `plan_quota`
also rides on every lease grant. **Unverified:** the live values, since asking requires a caller
credential this pass was not given.
### 2d. Not a source: the presence provider
CultLib's 10-29 presence provider attests Idunn-managed **service** liveness, not attention or work
(`libby-body:follow_up:presence-attention-not-carried`). It can answer "is the heartbeat unit up".
It cannot answer "is anyone working".
## 3. Smallest first cut
**Cut 1: one published read model, `swarm.work.v1`, from the Runs of the eight minds. No heartbeat,
no usage, no renderer.**
One record per instance (eight, key `<instance>`), derived and published by a single projector
(owner: the swarm-dashboard provider), holding only closed-set or id fields:
- `state`: `Working` (a Self run in force), `Turn` (a Persona run in force), or `Idle`.
- `run`: label of the newest in-force run, its `turn`, its start (from the admission header), else the
newest closed run's end.
- `on`: the claim id(s) and campaign slug(s), no free text.
- `observed_at` and the per-mind `as_of`, so a dead projector reads as stale.
This answers the stranger's question with typed state only. It deliberately omits `reason`,
`rationale`, `item`, `budget_usd`, and every `*_usd` field.
The Thing 2 surface for it is a `SurfaceDocument` that is a `Repeat` over those eight records, one
`thing.std.card` each, bound to `state` / `on` / the time fields. It can be authored and golden-tested
with the Rust contract on main. It cannot be seen until core (2a) and a backend exist. That is the
actual gating item, and it is not this cut's to work around with a Thing 1 or Eve surface.
Cut 2: add heartbeat liveness and the why-idle fields (`busy`, `released`, `waited_s`, `idle_s`,
`note`, `launches`), once the heartbeat publishes them as typed CultMesh state (it currently writes a
file only, and the dollar-denominated initiative model is under teardown).
Cut 3: add the `plan_quota` windows once a publisher polls the connector under a registered caller.
### Forks for the operator (recommendations given)
1. **Who is the stranger?** If public, the board shows ids and campaign slugs only (cut 1 as
written); "on what" in words needs a typed `public_label` that the claiming agent sets, not
`follow_up.item`. Recommend ids only until that field exists.
2. **Where does the projector live?** Recommend a small reader that queries the eight Huginns (all
answer today) and publishes `swarm.work.v1`, rather than adding publication to `mind-heartbeat`,
which is Idunn-managed with a single-file store and a dollar model in flux. Confidence moderate:
the cost is a new daemon, which needs the independent-lifecycle account `gamecult.md` requires.
3. **Is "open" enough?** Recommend marking `Working` only when a Run is in force **and** its
carrier is attested (the Run was admitted by a launch that is still live); the data for that
attestation is not in the Run. Until it is, say in the surface that `Working` means "admitted,
unresolved".
4. **Typed times.** Recommend asking Huginn for `started_at` and `ended_at` as Run/Resolution
document fields, so no consumer parses labels or header facts.
5. **Sequencing.** A stranger sees nothing until core and a backend land. If the swarm board should
come earlier than the TUI backend, say so; the TUI is the planned first backend and gives agents
a reader, but a stranger needs the web backend (map cut 4).
### Substrate gaps this pass felt
- The `swarm-dashboard-first-thing2-surface` ruling and the `thing2` campaign are in Eureka's mind,
not readable from libby's: cut status here comes from a 2026-10-12 prose map.
- `heartbeat.cc` unreadable from a Self run, and a file, not a served document.
- No typed `ended_at` / `started_at` on Run; outcome is free text in `reason`.
- No per-client read identity on the eight Huginns (`client unknown`).

825
docs/thing2-build-spec.md Normal file
View file

@ -0,0 +1,825 @@
# Thing 2.0 build spec
Status: build spec, refreshed 2026-11-10 against the thing2 rulings in force, on
top of `docs/thing2-target.md` (why, invariants) and
`docs/thing2-map.md` (body facts P1-P22, model page, consumer contract, authority
map, cut order). It does not restate them; it adds what the map leaves at
deliverable level: **the pieces, each piece's contract, the build order, and the
test that defends each piece**, with prior art for every design choice.
Nothing here overrides a ruling. Where this spec makes a choice the rulings do not
force, it is labelled **D<n>** (decision, with confidence) and the ones it could
not settle are in "Open" at the end, each with a recommendation.
## How to read the prior-art tags
Each piece ends with **Prior art**. Tags: **[read]** = a source read in an earlier
Eyes or Imagination pass, with its evidence pointer in `docs/research/*` (cited as
R-F = `thing2-foundation-prior-art.md`, R-T = `thing2-text-input-a11y-prior-art.md`,
R-K = `thing2-contract-forks-prior-art.md`, R-C = `thing2-consumer-census.md`);
**[background]** = prior knowledge, not re-fetched for this spec, and the first
thing to verify when its piece is mapped into a `cut_spec`. Confidence is stated
per decision. The standard is "prior-art sources cited"; O12 asks whether it
also fixes a format.
## 0. The machine in one page
```
provider ──publishes──▶ CultMesh state (typed .cc records)
│ StatePort (subscribe / read)
▼
┌───────────────────────── thing-core (one crate, internal modules) ─────────────────────────┐
│ resolve ─▶ bind ─▶ layout ─▶ text ─▶ render ─┐ │
│ (docs, (Bind, (Taffy) (Parley or ├─▶ FrameOutput { commands, a11y, outbound, │
│ compos.) Repeat) cells) │ ime, diagnostics } │
│ input (focus, edit, hit-test, scroll) ─▶ command dispatcher ─▶ outbound CommandInvocation │
│ a11y (AccessKit tree) │
└───────────────────────────────────────────────────────────────────────────────────────────┘
▲ FrameInput { now, viewport, scale, events } │ commands + a11y
│ ▼
host event loop ◀────── thin backend: TUI (crossterm) | web (wasm + JS) | later hosts
```
Core is a **function of (documents, state, input, time)**. The host owns the loop
and calls `Core::frame`; core never spawns, sleeps, reads a clock or touches a
socket except through a port. This is what makes every test below runnable without
a daemon (`doctrine/gamecult.md`, "dependency injection is boring") and what makes
goldens byte-stable (map rule 10).
**D1. One crate for core, internal modules, not eight crates.** (Confidence
medium-high.) Authority separation (resolve, bind, layout, text, render, command)
is real, but the modules share one frame pipeline and one set of types; a crate per
stage buys build fan-out and a public surface no consumer may use, which
`narrow-consumer-contract` forbids. Splits that *do* earn a crate, each naming the
invariant it protects:
| Crate | Earns its boundary because |
| --- | --- |
| `thing-contract` (landed) | consumers depend on it alone (`narrow-consumer-contract`); three runtimes are held to its goldens |
| `thing-core` | owns geometry, text, focus, binding, results; depends on no transport, no clock, no platform |
| `thing-mesh` | the only crate that depends on CultMesh/CultNet: `StatePort`/discovery implementations. Keeps rule 7 and the mockable-port invariant checkable by a dependency-tree grep on `thing-core` |
| `thing-tui` | backend; depends on `thing-core` output types and `crossterm`, never `taffy`/`parley` (rule 8) |
| `thing-web` | wasm entry (`wasm-bindgen`) plus the JS host package; same dependency rule |
| `thing-testkit` | fake ports, fixture loader, golden harness, shared by every crate's tests; never a dependency of a shipped artifact |
Prior art: Xilem and egui split by renderer/backends and keep one core
(R-K §1: `masonry_core`, `egui`+`epaint`, backends as crates) **[read]**; AccessKit
and Parley are separate repos only where independently consumed or needing another
toolchain (R-K §1) **[read]**; Flutter merged repos to end rolls (R-K §1)
**[read]**. Same repo, many crates, is the dominant pattern.
## 1. Build order and dependency graph
```
0 decisions ─▶ 1 contract-ts ┐
├▶ 1 contract-cs ┴▶ 1x cross-store check
└▶ 2 testkit+ports ─▶ 3 resolve ─▶ 4 bind ─▶ 5 layout ─▶ 6 render+goldens ─▶ 7 commands
│ │
8 TUI ◀────────┘ │
9 text(Parley)/focus/edit ─▶ 10 a11y ─▶ 11 web ◀───┘
12 thing-mesh (parallel from 4 on)
13 consumer ports (one per consumer) ─▶ 14 retirement
```
Rules for the order: (a) contract before core (map, rationale); (b) the pipeline is
built **end to end thin first** (cut 8 draws a real surface in a terminal before
text, IME or a11y exist), then deepened, because the first full run is where unknown
unknowns show; (c) `thing-mesh` runs beside core from cut 4 because it is the
other half of the `StatePort` contract and needs the same fixtures; (d) no consumer
port starts before cut 7 and one backend (cut 8) work, so a port can be viewed.
Cuts are sized to Hands' budget (about 150 calls, 0.5M tokens is the danger line):
each row below is one `cut_spec`, or two where marked. Sizes are Self's estimates
in thousand lines of owned code (excluding goldens), pressure not metric.
| # | Cut | Waits on | Est. | Parallel with |
| --- | --- | --- | --- | --- |
| 1a/1b | contract-ts, contract-cs (specs `thing2:cut_spec:cut-contract-ts.r3`, `-cs.r3`) | contract-rs (landed `6ae2da0`) | mapped | each other |
| 1x | cross-store check | 1a, 1b | 0.3 | 2 |
| 2 | testkit + ports | contract-rs | 1.2 | 1a, 1b |
| 3 | resolve | 2 | 1.8 | - |
| 4 | bind | 3 | 1.5 | 12 |
| 5 | layout | 4 | 1.8 | - |
| 6 | render + goldens | 5 | 1.5 | - |
| 7 | commands | 4 (needs 6 only for hit-test) | 1.6 | 8 |
| 8 | TUI backend | 6, 7 | 1.5 | 7 tail |
| 9a/9b | text: measure+shape, then focus+editing+IME state | 6 | 2 + 2 | 8 |
| 10 | a11y tree | 9b | 1.0 | 11 start |
| 11a/11b/11c | web: wasm+drawing, IME mirror + a11y mirror, shell+discovery | 6, 9b, 10 | 1.5+1.5+1.0 | - |
| 12 | thing-mesh | 2, 4 | 1.5 | 5-8 |
| 13.n | consumer ports | 7, 8 (web for browser consumers: 11c) | per consumer | one repo each |
| 14 | retirement | last port | -1x | - |
## 2. Cross-cutting contracts
### 2.1 Core API (the one public surface core has)
```
Core::new(ports: Ports, config: Config) -> Core
Core::frame(&mut self, input: FrameInput) -> FrameOutput
FrameInput { now: Instant, viewport: Size, scale: f32, events: Vec<InputEvent>, metrics: MetricsMode }
FrameOutput { commands: Vec<RenderCommand>, a11y: Option<TreeUpdate>, outbound: Vec<CommandInvocation>,
ime: Option<ImeRequest>, diagnostics: Vec<Diagnostic>, next_wake: Option<Instant> }
Ports { state: dyn StatePort, fonts: dyn FontPort, clock: dyn Clock, ids: dyn IdSource, host: dyn HostEffects }
```
- **One owner for time and ids.** `now` arrives in the frame input; `IdSource`
mints invocation ids. Tests substitute both, so a run is a pure function and
invocation ids in goldens are reproducible.
- **Outbound is invocations only** (rule 7). `Ports.state` has `read`, `subscribe`,
`list(schema, key_prefix)`; it has no `write`. The one write path is
`FrameOutput.outbound`, which the host or `thing-mesh` forwards.
- **`HostEffects`** has exactly the closed `effect` set of the contract:
`open_surface(key)`, `open_external(url)`; plus `clipboard` read/write when the
text piece needs it (see Open O7).
- Metrics mode (`Pixels` | `Cells`) is a core input, because the TUI measures in
cells inside the Taffy measure function (R-T §5: iocraft does exactly this
**[read]**) and rule 8 forbids the backend from owning any layout input. The
cell-metrics provider is part of core (small: `unicode-width` and
`unicode-segmentation`), not of `thing-tui`.
Prior art: Clay's per-frame contract (set dimensions → pointer state → begin layout
→ end layout returns the command array) is the model for `frame` **[read, R-F
§2.1]**; egui and Bevy UI emit shapes or commands to thin backends **[read, R-F
§2.4, R-T §1]**. Elm/Redux style "update is a pure function of state and event"
**[background]**. Confidence high: no contrary evidence found.
### 2.2 The closed render-command list (D2)
`FillRect{rect, radius, color}`, `StrokeRect{rect, radius, width, color}`,
`Text{origin, run, color}` where `run` is `Glyphs{font, size, glyphs}` (Pixels mode)
or `Cells{col, row, text, style}` (Cells mode), `Image{rect, catalog, asset, fit}`,
`ClipPush{rect, radius}`, `ClipPop`, `Polyline{points, width, color}`,
`Polygon{points, color}` (plot marks), `Embed{rect, slot_kind, slot_id}`.
Nine variants. Selection highlights, carets, focus rings and scrollbars are
`FillRect`/`StrokeRect` that core emits. Z order is emission order; there is no
z-index, no layers, no custom escape. A new command is a reviewed change to core
plus every backend and the goldens at once (that is the point of closing it).
Colours in commands are resolved literals; theme tokens never cross to a backend.
Coordinates are `f32` logical pixels in Pixels mode, integer cells in Cells mode.
Prior art: Clay's complete enum is `NONE, RECTANGLE, BORDER, TEXT, IMAGE,
SCISSOR_START, SCISSOR_END, OVERLAY_COLOR_START/END, CUSTOM`, with renderers for
SDL, raylib, canvas2d, termbox2 and a terminal, all thin **[read, R-F §2.1]**.
Thing's list differs on purpose: no `CUSTOM` (Embed is the closed host slot), no
overlay-colour pair (an overlay scrim is a `FillRect`), plus polylines for `Plot`.
Confidence medium: the count is a proposal; whether `Plot` should lower to
`Polyline`/`Polygon` or be left to an `Embed` is O3.
### 2.3 Diagnostics (D3)
A closed `Diagnostic { code, node, document, detail }`: `UnresolvedUse`,
`BindSchemaMismatch`, `BindMemberMissing`, `UnknownNode`, `UndeclaredCommand`,
`DuplicateNodeId`, `StaleVersionIgnored`, `MalformedResult`, `UnknownInvocation`,
`InvocationTimedOut`, `DecodeRefused`. The same value drives (a) the placeholder or
error node drawn in the frame, (b) a log line, (c) the a11y tree (an error node is
announced), and (d) the tests. Rules 2, 4, 5 and 6 are asserted on these codes, so
a rule that is deleted fails by name, not by a screenshot.
Confidence high; the alternative (free-text logs) is what Thing 1's gap ledgers were.
### 2.4 Test layers and golden format (D4)
Doctrine splits tests into local-authority unit tests, adjacent-organ pipeline
smokes, and end-to-end Verse contract runs; every piece below names which layer.
- **Fixtures** (`tests/fixtures/*.surface.cc`, committed): typed documents encoded
through `thing-contract`, one per row of the fixture table (§2.5). Built by a
`thing-testkit` builder in Rust, then frozen; the bytes are what is loaded.
- **Geometry golden**: for a fixture + viewport + state script, the resolved node
tree with `(node id, x, y, w, h)` in a stable text form.
- **Render golden**: the `Vec<RenderCommand>` encoded with CultCache MessagePack
through the same derive the contract uses, plus a line-oriented text rendering
beside it for diffs. The binary form is the oracle (byte-identical, rule 10); the
text form is only for review.
- **Regeneration** is `cargo xtask bless`, runs only on a reviewed core change,
and a backend crate cannot call it (model page: goldens are the core's).
- **Layout correctness is inherited, tree building is tested.** Taffy is itself
validated against Chrome with generated fixtures (`just gentest`, R-F §2.2
**[read]**), as is Yoga (`gentest/`, R-F §2.3 **[read]**); Thing does not re-prove
flexbox. Thing's tests prove that *our* style mapping puts the right inputs into
Taffy and that the output flows into commands unchanged. One extra check
re-derives a small fixture's geometry from the raw Taffy API directly and compares
(guards against our mapping drifting while goldens are re-blessed).
- **Mutation**: `tools/cargo-mutants.sh` once per Hands pass, scoped to the cut's
diff, per the Eureka rule. Each piece's "Test" below names the rules whose
mutants must die; a survivor is triaged, not hidden.
- **Property tests** (`proptest` [background]) only where a total function has a
clear law: contract round-trip (exists), `resolve` never panics and either
returns a tree whose ids are unique or a refusal, `bind` is idempotent for the
same state, `frame` with no events and unchanged state returns an equal command
list (stability). Fuzzing the decoder (`cargo-fuzz` [background]) waits only on Eve taking the
CultLib pin that carries `decode-stack-safety` (Fixed, CultLib `bbb98eaf`,
`cultlib-gaps:resolution:follow_up.decode-stack-safety.n1`; map P20).
Prior art: golden command lists are not published by any project read (R-F §2.5:
"not found, not searched exhaustively"), so this is the least-supported decision
in the spec; the nearest supported techniques are Taffy/Yoga generated geometry
tests and egui's `egui_kittest` snapshot crate (R-K §1 lists the crate;
its snapshot method is **[background]**). Confidence medium: the idea is sound
because commands are renderer-independent by construction; cost of churn on
intentional change is the risk, mitigated by `bless` being one command.
### 2.5 Fixture set (the census sizes the floor)
Twelve fixtures cover the node set and every rule; each is named for the consumer
shape it models (R-C §7 cross-table is the source, and Thing is a general library,
so a fixture exists for a capability a reasonable consumer would expect even with
no caller today):
| Fixture | Exercises | Rules |
| --- | --- | --- |
| `f01-swarm-dashboard` | VoidBot-shaped: Box grid, bound Text/Format, `Repeat` over a collection prefix, one Button | 6, 9 |
| `f02-login-effect` | Ghostlight/Heimdall: TextInput, Button, `OpenExternal{resume}` result | 1, 2 |
| `f03-input-target` | Muninn: `position: absolute` target over an `Image`, bound label (P6) | - |
| `f04-form` | Toggle, Slider, Select, TextInput number, `captures` and `clear_drafts` | 1 |
| `f05-modal-overlay` | `Overlay` modal with dismiss command, focus trap | - |
| `f06-scroll-list` | `overflow: scroll`, `Repeat` 1k items, keyed insert/remove | - |
| `f07-plot` | Stonks/StreamPixels-shaped `Plot` series | - |
| `f08-embed-viewport` | `Embed` slot as a leaf of given size | - |
| `f09-composition-stack` | nested `Use` with typed args and child slots, `thing.std` plus a publisher composition | 5 |
| `f10-hostile` | unknown arm, undeclared `CommandRef`, duplicate id after expansion, unresolved `Use`, schema-mismatched `Bind` | 4, 5, 6 |
| `f11-deep` | nesting at the 256 bound (decoded on a large-stack thread until Eve's pin of CultLib `bbb98eaf` merges) | - |
| `f12-text-edge` | bidi, CJK wide characters, combining marks, emoji ZWJ, long wrap | - |
## 3. The pieces
Each piece lists **Owner** (one writer), **In**, **Out**, **Ports**,
**Invariants** (what must die under mutation), **Failure**, **Test** (layer and the
rule each pins), **Deletes/forbidden** (what the piece must not contain), and
**Prior art**. Map rules are cited as M1-M10 (the ten in the map's "Rules that must
die under their own mutation").
### Piece 1: contract (packages for TS and C#, and the store check)
Rust (`crates/thing-contract`) landed after two Soul passes; `contract-ts` and
`contract-cs` are mapped (`thing2:cut_spec:cut-contract-ts.r3`, `-cs.r3`; r2
is superseded) and have
branches (`hands/thing2-contract-ts`, `hands/thing2-contract-cs`) not yet merged.
This spec adds no contract change. Rulings that bind the packages:
- **Unknown union arms** are refused by CultCache in every runtime, the C#
reference included, and Thing packages carry no check of their own
(`thing2:ruling:contract-decode-tolerance`; the fix is CultLib's, follow-up
`thing2:follow_up:cultcache-union-parity`, resolved in the mind). The "unknown union arm is refused"
test below therefore exercises CultCache, not package code.
- **Nil in required slots** is refused by each package: constructors and factories
reject null, decoding nil into a slot the Rust contract does not make optional
is a typed refusal (`thing2:ruling:contract-refuses-nil-in-required-slots`,
Defaulted). In TS this is a `present(codec)` on every non-Option slot, and
results are validated and frozen at one factory (`cut-contract-ts.r3`).
- **Byte payloads** (`RecordPayload.Bytes`) are a copied read-only view in C#
(`ReadOnlyMemory<byte>`); Rust's `Vec<u8>` and the wire are unchanged
(`thing2:ruling:payload-bytes-read-only`, Defaulted). The catalog type name for
that slot changes with it, which the 1x store check must read from the C# set.
- **Owner:** the contract crate; packages own nothing (map authority).
- **Test (per package):** the shared golden fixtures decode and re-encode
byte-identical (M1, M3); the refusal goldens (`seq` 0, extra slot, unknown union
arm) are refused; a hand-built object with seq 0 is refused at encode.
- **1x cross-store check:** the C# package opens a `.cc` store the TS package wrote
and the reverse, and both open Rust's. The check lives in `thing-testkit` as a
scripted cross-runtime job run on Yggdrasil's verify stopgap
(`tools/stopgap/ygg-verify.sh`), because only that image has all three runtimes.
It proves the catalog type names agree (map cut 1 waiting line).
- **Prior art:** CultCache wire parity against the C# reference is the standing
CultLib rule; probe P12-P13 are the evidence **[read, map]**; golden-file
interoperability is how Protobuf and Cap'n Proto test language bindings
(`conformance` suites) **[background]**. Confidence high.
### Piece 2: testkit and ports
- **Owner:** `thing-testkit` owns fakes; `thing-core` owns the port *traits*
(a trait is the narrow port; the fake is a test crate's business).
- **In/Out:** `StatePort { read(schema,key)->Option<Entry>, list(schema,prefix),
subscribe(schema,key|prefix) -> Stream<Change> }` where `Change` is
`Upsert(entry)|Delete(key)`; `FontPort { resolve(family, weight, style) ->
FontHandle, bytes(handle) }`; `Clock`; `IdSource`; `HostEffects`. All object-safe.
- **Fakes:** `MemState` (a `CultCache`-backed map with a scripted change feed and
a record of every call), `FixedFonts` (one bundled test font, so Parley output is
deterministic across machines), `ManualClock`, `SeqIds`.
- **Invariants:** `StatePort` has no write method (M7, checked by the trait's
method list in a test that enumerates it and by a grep over `thing-core`);
`MemState` returns entries only as decoded contract records, never `Value`.
- **Failure:** a decode refusal from the port surfaces as a `Change::Refused`
carrying the code, never as a missing record (a refusal must not look like
absence).
- **Test:** unit. `MemState` change ordering; fixture loader round-trips all twelve
fixtures through the contract (a fixture that fails the contract is a bug in the
fixture before it is a bug in core).
- **Deletes/forbidden:** no global state, no `Instant::now()` in core (negative
grep).
- **Prior art:** the port style is the project's own doctrine; Xilem's
`masonry_testing` and egui's `egui_kittest` are test-harness crates beside a core
(R-K §1) **[read]**. Confidence high.
### Piece 3: resolve
- **Owner:** `thing-core::resolve`. It is the only code that interprets Thing
Script structure.
- **In:** `SurfaceDocument`, a `CompositionStore` (std compiled in, plus publisher
compositions read through `StatePort`). **Out:** `ResolvedTree` (arena of
nodes, unique ids, every `Use` expanded or replaced by a placeholder node, every
`CommandRef` checked against the document's `CommandDecl`s, bindings still
unresolved), plus diagnostics.
- **Invariants:** M4 (unknown kind, undeclared `CommandRef`, duplicate id after
expansion refuse the document *whole*, and the old document stays displayed);
M5 (unresolved `Use` is a visible placeholder with a diagnostic); expansion is
substitution only (no conditionals, no arithmetic: a test that every
`thing.std` composition expands under a parameter-less evaluator); expansion
terminates (recursion in compositions is refused with a cycle diagnostic and a
depth bound); expansion is deterministic and order-preserving; ids of expanded
nodes are derived from the `Use` node id and the template id by one scheme, so
they are stable across republishes (focus and scroll state key on them).
- **Failure:** a referenced composition arrives later → the placeholder is
replaced next frame without a republish.
- **Test:** unit per rule on `f09`, `f10`; property (`resolve` total, ids unique or
refusal); pipeline smoke: `resolve` output fed to `layout` (cut 5) in `f01`.
Mutants that must die: skip the duplicate-id check; treat an undeclared
`CommandRef` as a warning; drop the placeholder; expand `Use` without pinning the
composition version.
- **Deletes/forbidden:** no `kind` string dispatch anywhere (closed enum only); no
fallback along a kind path (M4); no expression evaluator. No text-syntax parser
outside `thing-core` (`thing-script-form`): `resolve` consumes only the typed
document; a later `.thingscript` parser is core's and feeds it.
- **Prior art:** Adaptive Cards separates template expansion from render
(`adaptivecards-templating` expands a template against data before render)
**[read, R-K §2]**; Thing's `Use` is the same split without an expression
language, which R-K §2/P5 shows the failure of (the DSL's renderer-local `derive`)
**[read]**. Slint compiles a text language to a typed tree at build/run time
**[read, R-K §2]**. Confidence high on substitution-only; medium on id-derivation
(no source read; it is the same problem React solves with keys **[background]**).
### Piece 4: bind
- **Owner:** `thing-core::bind`. Only code that reads typed state.
- **In:** `ResolvedTree`, `StatePort`. **Out:** `BoundTree` with every `Bind`
replaced by a typed value or a binding-error value; `Repeat` expanded to one
subtree per item, keyed by the item key; subscriptions established and released
as bindings appear and disappear.
- **Invariants:** M6 (different schema or missing member renders a typed error,
never a coerced value); M9 (a version at or below the held one is ignored, and
the ignore is a `StaleVersionIgnored` diagnostic at most once per document
version, not per frame); a value change never triggers layout of anything but the
nodes whose bound values changed (dirty tracking is observable through a counter
the test reads); `Format` is total and locale-free in core (formats are the
closed set; any locale is a host input, see O8); `Repeat` item keys must be
unique, a duplicate key refuses the document at bind time as M4 does; keyed
reorder preserves node identity, so focus and scroll survive a reorder.
- **Subscription rule:** core subscribes to exactly the `(schema,key)` pairs and
prefixes the live tree references; a document replacement diffs its subscription
set. An unsubscribed record's arrival changes nothing.
- **Failure:** record absent → a typed `Absent` value rendered as the node's
declared empty text (the contract field), not an error; schema mismatch → error.
- **Test:** unit per rule on `f01`, `f06`, `f10` with scripted `MemState` feeds;
pipeline smoke `bind → layout` checks dirty-node count; mutants: coerce a
mismatched schema; drop the version gate; resubscribe every frame; reorder by
index instead of key.
- **Deletes/forbidden:** no local `var`/`derive`/`collection` store (P5); no draft
binding (BD2: editing state is `input`'s).
- **Prior art:** BD1-BD9 collapse in the map **[read, map]**; keyed list
reconciliation is React's `key` and Elm's `Html.Keyed` **[background]**;
Clay retains element state by ID and requires `CLAY_IDI` for loops (R-F §2.1)
**[read]**, the same constraint. Flutter's retained tree keeps state by key
**[background]**. Confidence high.
### Piece 5: layout
- **Owner:** `thing-core::layout`. The only crate-user of `taffy`.
- **In:** `BoundTree`, viewport, metrics mode, `FontPort`. **Out:** `LaidTree`:
per node a content box, scroll extents, clip, and absolute-positioned overlay
boxes.
- **Contract:** the mapping from contract `BoxStyle` to Taffy style is one
function with an exhaustive match (a new contract field fails to compile until it
is mapped). Leaf measure for `Text`, `TextInput`, `Image`, `Embed`, `Plot`
goes through one `Measure` trait: Pixels → Parley (piece 9), Cells → cell metrics,
`Image`/`Embed`/`Plot` → declared sizes. Overlay nodes are laid out as a
separate root attached to an anchor node's final rectangle or the viewport.
Scroll containers expose `content size` and clamp offsets that `input` owns.
- **Invariants:** layout is a pure function of (tree, viewport, scale, metrics,
fonts): same inputs, byte-identical geometry (M10); a style field with a literal
and a token resolves via the one theme resolver before reaching Taffy; `fr`,
`%`, `auto` and `content` sizes reach Taffy as the matching Taffy dimensions
with no rewriting; an `Embed` is a leaf of exactly its declared size.
- **Failure:** NaN or negative sizes from a document are refused at resolve (the
contract already refuses at decode for `Count`); layout never panics on a
constraint it cannot satisfy and instead overflows per CSS rules.
- **Test:** unit geometry goldens on `f01`, `f03`, `f05`, `f06`, `f08`; the
raw-Taffy rederivation on one small tree (§2.4); property: layout is
deterministic across repeats and scale 1 vs 2 scales positions linearly when
fonts are scale-independent (fixed font); Cells mode: `f12` widths equal
`unicode-width` expectations. Mutants: swap row/column mapping; drop `gap`;
round positions; ignore `position: absolute` insets.
- **Deletes/forbidden:** `taffy` appears in no other crate's tree (M8, `cargo tree
-i taffy` negative check on `thing-tui`, `thing-web`, `thing-mesh`, contract).
- **Prior art:** Taffy implements Block, Flexbox and Grid, is used by Servo, Blitz,
Bevy, Slint, iocraft, Zed/GPUI and is validated against Chrome (R-F §2.2) **[read]**;
measure-function leaf text is the documented integration point (R-F §2.2, R-T §1)
**[read]**; iocraft's measure for Cells (R-T §5) **[read]**. Ruling
`thing:ruling:thing2-one-solver-taffy`. Pin: Taffy 0.14.0 (2026-08-24 [read]);
Slint pins 0.10 flexbox-only and iocraft 0.5.2 (R-T §1, §5), so the Grid feature
surface at 0.14 is the one to prove first (confidence medium).
### Piece 6: render and goldens
- **Owner:** `thing-core::render`. Turns `LaidTree` + paint + input state into the
command list; draws selection, caret, focus ring, scrollbars.
- **Invariants:** M10 (byte-identical command list for equal inputs); painter
order is document order, then overlays last; `ClipPush`/`ClipPop` balance (a
validator over every golden); every `Embed` and `Image` node produces exactly
one command or a visible missing-asset placeholder (diagnostic `AssetMissing`
added to D3's list when this cut lands, O9); nothing outside the clip stack is
drawn for `overflow: clip|scroll` nodes.
- **Backends must prove consumption (M10 second half):** each backend's parity
test replays a golden list and asserts one draw call per command; a backend that
skips a command variant fails by name.
- **Test:** golden suite described in §2.4 over all fixtures; pipeline smoke
`resolve→bind→layout→render` on `f01`; mutants: drop `ClipPop`, reorder overlay,
emit caret when unfocused, emit a command with a theme token not a literal.
- **Prior art:** Clay's sorted command array and scissor start/end (R-F §2.1)
**[read]**; egui/epaint clipped shapes to thin backends (R-F §2.4) **[read,
background]**. Confidence high on structure, medium on exact variants (O3).
### Piece 7: commands (dispatcher and result validation)
- **Owner:** `thing-core::command`. Mints invocations, tracks them, validates
results. The only producer of `FrameOutput.outbound`.
- **Lifecycle (D5):** `Issued → Pending* → Completed | Denied | Failed`, with two
core-only terminal states, `Malformed` (result failed to decode, or named an
unknown invocation) and `TimedOut`. Terminal states are final: a later result
for a terminal invocation is a diagnostic, not a state change.
- **In:** input events that activate a `CommandRef` node; results arriving as
`StatePort` changes of schema `gamecult.thing.command_result.v1`.
**Out:** `CommandInvocation` (id from `IdSource`, `captured` from `input`'s editing
state for the nodes `CommandDecl.captures` lists, `surface` = key + held version,
`issued_at` from the clock; **no caller identity field written**, the transport
sets it), UI state for the issuing node (busy, denied-at-node), effects through
`HostEffects`.
- **Invariants:** M2 (a result that fails to decode, or an unknown `invocation_id`,
becomes a visible `Malformed` state for that invocation and a log line; no
invocation stays pending past its timeout without one); M7 (core writes nothing
but invocations); idempotency: one user action mints exactly one id, and a
re-delivered invocation carries the same id; `Completed{clear_drafts:true}`
clears exactly the captured nodes' drafts and no others; `OpenExternal{resume}`
is executed once per result `seq`; a `Denied{node}` marks that node and no
other; a double-click on a busy Button mints no second invocation while the first
is non-terminal (the Button node's enabled state is derived from lifecycle, not a
flag a document sets).
- **Timeout:** a core config value, default 15 s in `Config` (O5: it is a guess).
- **Failure:** `StatePort` refusal on a result (piece 2's `Change::Refused`) maps to
`Malformed`, which is the case P2 shows Thing 1 lacked (result rejected whole
by `ajv` with nothing visible).
- **Test:** unit lifecycle table (every transition, every illegal one), driven
with `ManualClock` for timeouts; pipeline smoke with `MemState`: press a Button in
`f02`, assert exactly one outbound invocation with the right captures, feed
`Pending` then `Completed{OpenExternal}`, assert one host effect; negative:
result with extra field (M1) never reaches the lifecycle. Mutants: no timeout;
mint id per frame; `clear_drafts` clears all; accept results after terminal;
write caller identity.
- **Prior art:** idempotency keys for commands and retries (Stripe API
idempotency, RFC draft "Idempotency-Key" header) **[background]**; command/result
split with a pending phase (job/operation resources in Google AIP-151 long-running
operations) **[background]**; Flutter's `TextInputConnection` shows what drafts the
host must hold (R-T §4) **[read]**. Evidence of the failure it prevents: P2, P7
**[read, map]**. Confidence medium-high; the `Malformed` rule follows directly
from P2.
### Piece 8: TUI backend (`thing-tui`)
- **Owner:** `thing-tui`: terminal drawing, keyboard and mouse into `InputEvent`.
First end-to-end consumer of core; also the agents' reader.
- **In:** `FrameOutput.commands` in Cells mode. **Out:** terminal bytes via
`crossterm`; `InputEvent`s.
- **Invariants:** M8 (no `taffy`/`parley` in the tree); every `RenderCommand`
variant is handled and each is either drawn or explicitly declared
not-representable in cells (`Image` → block placeholder with alt text,
`Polyline` → braille or block approximation): "not representable" is a table in
the crate, tested; wide and zero-width characters advance the cursor as the
`Cells` run says (the backend never re-measures); the screen diff writes only
changed cells (testable on a `Vec<Cell>` buffer without a terminal).
- **Test:** unit on a virtual screen (`ratatui`-style test buffer is
**[background]**; ours is a `Vec<Cell>`): every golden command list renders to a
stored screen dump; pipeline smoke: `f01` through the whole of cuts 3-7 to a
screen dump; parity (M10): every command variant produces a cell effect.
Mutants: skip `ClipPop`; mis-advance on a wide char; draw a command outside the
clip; ignore `Text` colour.
- **Forbidden:** layout of any kind.
- **Prior art:** Clay has `termbox2` and terminal renderers as thin command
consumers (R-F §2.1) **[read]**; iocraft is a Taffy-based TUI (R-T §5) **[read]**;
ratatui uses Cassowary not Taffy and pins `unicode-width >= 0.2.0` (R-T §5)
**[read]**, a version issue to carry into our own pin (confidence medium: width
tables differ between 0.1.x and 0.2.x, so the cell widths in goldens must be
pinned to a crate version, D6).
### Piece 9: text (9a measure+shape, 9b focus+editing+IME state)
- **Owner:** `thing-core::text` (`thing:ruling:thing2-thing-owns-text`, operator:
core owns shaping (Parley), editing and IME state, focus and the AccessKit tree;
backends only draw and bridge to platform protocols; glyph rasterization stays
backend-private and the render-command contract carries shaped glyph runs).
- **9a In/Out:** string + `TextStyle` + width constraint → `TextLayout` with
line boxes and glyph runs (Pixels, via Parley) or cell lines (Cells). One
`Measure` implementation per metrics mode behind the layout `Measure` trait.
- **9b In/Out:** `InputEvent`s targeted by hit-test/focus → editing state per
`TextInput` node (value, selection, composition range), caret rectangle,
`ImeRequest { rect, text_window, selection }` (the data a hidden host element
needs), and edits fed to `command` as captured values.
- **Focus (D7):** one focus owner in core. Tab order is document order of
focusable nodes, overlays trap focus while modal, focus is keyed by node id and
survives republish when the id survives, and a focused node removed moves focus
to its previous sibling then parent. A backend never owns focus; it forwards host
focus loss/gain only.
- **Invariants (9a):** shaping and bidi never run in a backend (M8); a run's glyph
positions are a pure function of (text, style, width, font bytes); wrap and
`max_lines` are applied by core and appear in the command list.
- **Invariants (9b):** the draft is core's state and dies with the session (model
page row 5); composition text is displayed but not committed or captured until
the host commits; an IME update never rewrites committed text; every selection
edit is on grapheme-cluster boundaries (`unicode-segmentation`); `ImeRequest`
windows the text rather than mirroring a whole large value, and coalesces to one
per frame (R-T §2: GPUI's mirror coalesces writes because each write restarts the
IME connection **[read]**).
- **Test:** 9a: unit on `f12` (bidi order, CJK width, combining marks, ZWJ
emoji clusters, wrap at several widths) with the bundled font; golden glyph
runs. 9b: scripted event sequences (type, move, select, delete across a
cluster, compose-update-commit, compose-cancel, undo if D8 includes it) assert
value/selection/`ImeRequest` at each step; focus: traversal order on `f04`,
trap on `f05`, removal on a republish. Mutants: byte-index deletion in a
cluster; commit composition on update; focus not keyed by id; mirror whole value.
- **Prior art:** Parley: rich-text layout with HarfRust shaping, ICU4X bidi and
segmentation, `PlainEditor`, IME primitives, an AccessKit editor example
(R-T §1) **[read]**; Bevy (taffy 0.14 + parley 0.11), Slint (`shared-parley`),
Blitz (Stylo + Taffy + Parley, text input state in the DOM node), Masonry (R-T §1-2)
**[read]**: four independent Taffy+Parley integrations. Cosmic-text is the
alternative; Parley wins on the integrations above and AccessKit ties, not on
measured quality (R-T §1; no benchmark read). IME-restart and mirror behaviour
from GPUI web, egui `text_agent`, Flutter web `text_editing.dart` (R-T §2)
**[read]**. Confidence medium: all of this is an assembly of read-but-not-built
parts; the biggest risk is Parley under `wasm32` and `no_std`-adjacent builds
(not established; O1). Slug/Vello GPU glyphs (R-T §6) is the operator's scope
addition and is **out of this build order**: glyphs reach the backend as
positioned runs, and how the web backend rasterizes them (canvas 2D first,
GPU later) is O2.
### Piece 10: a11y tree
- **Owner:** `thing-core::a11y`. Derives an AccessKit `TreeUpdate` per frame from
the resolved tree, roles, labels, focus, text editing state and layout.
- **Invariants:** every focusable node has a role and an accessible name (a
document that offers none gets the diagnostic `NoAccessibleName`, O9); roles come
from the contract's closed `Role` set mapped by one exhaustive match; bounds equal
layout bounds; updates are incremental (unchanged nodes omitted), keyed by node
id; an `Embed` is exposed as a generic node with its label; text input exposes
value, selection and composition as AccessKit text-run data.
- **Test:** unit: tree for `f01`, `f04`, `f05` compared to stored AccessKit
dumps; incremental update test (change one bound value → exactly the changed
node plus ancestors needed); mutants: drop `focus`; stale bounds after scroll;
role map swap. An actual screen reader cannot be run in CI; it is an operator
check at web cutover (O6).
- **Prior art:** AccessKit as the schema, with Bevy, Blitz, Masonry, Slint, GPUI
and egui integrating it (R-T §3) **[read]**; Blitz's `build_accessibility_tree`
tests (`accessibility_roles.rs`) are the closest test style **[read]**. Web
adapter: **planned only** in AccessKit (R-F §2.6, R-T §3), so the web backend
mirrors the tree to DOM itself (piece 11b); Flutter web is the shipped precedent,
and its open issues (semantics DOM stealing taps, R-T §3) are the failure
catalogue for 11b. Confidence high on native, medium on web.
### Piece 11: web backend and shell (`thing-web`)
- **Owner:** `thing-web` (wasm entry + a small JS host package). Replaces the
Nightwing browser reference (`nightwing-eve-browser-reference`, P8).
- **11a draw:** core compiled to wasm, `frame` called from `requestAnimationFrame`
with batched events; commands drawn to one canvas 2D context (D9: canvas 2D
first, because GPUI web already rasterizes through OffscreenCanvas 2D, R-T §2,
and the contract is already glyph-run based so a GPU path swaps in under the same
commands). The JS host holds **no layout, no text shaping, no focus state**.
- **11b IME + a11y:** a hidden `<textarea>` placed from `ImeRequest` (the pattern
all three of egui, GPUI and Flutter web converge on, R-T §2), mirrored text
windowed and coalesced; a DOM accessibility mirror of the AccessKit update,
clipped so it cannot intercept pointer events (the exact Flutter failures in R-T
§3: #194011, #192466), off by default until an assistive-technology signal or an
explicit toggle, as Flutter does.
- **11c shell + discovery:** a web app that discovers surfaces through the Verse's
discovery owner (map: discovery is not Thing's, `advertisement-owner`; until the
owner's typed advertisement lands, `thing2:follow_up:discovery-owner-campaign`,
through one adapter over today's `gamecult.eve.provider_advertisement.v1`,
deleted when it does) and mounts core; reachable by `thing-mesh`'s transport or a gateway (O4).
- **Invariants:** M8 (no `taffy`/`parley` in the JS package or the wasm host
glue); the JS host calls only `Core::frame`, passes only the closed
`InputEvent`s, and draws only the closed commands; the hidden textarea never
scrolls the page into view (R-T §2: egui's park-over-canvas) and never receives
pointer events; one frame's work for `f06` (1k items) stays under a stated budget
(O10: a number is owed, none was measured).
- **Test:** unit in `wasm-bindgen-test` (headless Chrome and Firefox in the verify
image): replay goldens through the canvas and compare against a canvas-drawn
reference of the same list (command consumption, M10); IME: scripted composition
events at the textarea produce core edits equal to the 9b scripts; a11y: DOM
mirror equals the AccessKit tree for `f04`; click-through: a pointer test over a
mirror region reaches the canvas target (guards the Flutter failure). Real IME
and real screen readers are operator checks (O6).
- **Prior art:** R-T §2-3 as above; EditContext is Chrome-only (MDN, R-T §3) so it
is not the base path; `egui` web and Flutter web **[read]**; Slint web has no
accessibility and is not recommended for general web apps (R-T §2) **[read]** (the
failure this piece exists to avoid). Confidence medium: no Taffy+AccessKit
web combination exists in the sources read (R-T Gaps), so 11b is first of its
kind for this stack.
### Piece 12: thing-mesh (the CultMesh adapters)
- **Owner:** `thing-mesh`: `StatePort` and a discovery client over CultMesh/CultNet
and CultCache (the client is a port: Thing's contract has no advertisement of its own, `advertisement-owner`); the outbound invocation sender; the only crate with a transport
dependency.
- **Invariants:** a `StatePort` never returns `serde_json::Value` or an untyped
blob (P3); decode runs through the contract types and refuses on error
(`Change::Refused`), never a silently-dropped update; subscription uses the mesh's
own mechanism, never a poll loop (BD9 dies); the sender sets the caller identity
from the transport session and has no API to override it; decode needs no special thread once Eve pins CultLib `bbb98eaf`, which
carries `cultlib-gaps:follow_up:decode-stack-safety` (Fixed); until that pin
merges, decode runs on a thread with the stack it needs (P20).
- **Test:** pipeline smoke: a real CultMesh in-process loopback publishes
`f01`'s state and a document; core with `thing-mesh` shows it; then a hostile
record (unknown arm) yields `Change::Refused`; an invocation sent through the
sender arrives at a fake provider with the transport's identity and not any value
the core supplied. End-to-end (per Verse contract): later, with Odin's discovery.
- **Prior art:** the doctrine itself (CultMesh is the state substrate;
`doctrine/gamecult.md`); service registries are not owned by the UI toolkit
(R-K §3: Consul, Kubernetes Services **[background]**; Teams manifests vs cards
**[background]**). Confidence high on shape, unknown on the CultMesh API surface
it must wrap: that API is read when the cut is specced (O4).
### Piece 13: consumer ports (template)
One `cut_spec` per consumer, each carrying its rename (T, E1-E7 in
`thing-campaign.md`) and deleting its Thing 1 path in the same cut. Order per map
cut 5 (Odin, VoidBot, Ghostlight+Heimdall, Muninn/sleipnir, weksa, Stonks, Vili,
Gjallar, StreamPixels, gamecult-ops, CultLib), with cutover shape per
`thing2:ruling:port-cutover`: live consumers cut over one at a time, never all at
once.
Rulings that shape every port:
- **Naming and wire.** The eve-to-thing wire rename is frozen and folded into Thing
2.0; no wire, window or prose rename lands apart from a port. Thing 2.0 adopts
rename table T and edge table E1-E7 as its naming rule, so surviving kinds are
born `gamecult.thing.*` (`thing:ruling:wire-rename-freeze-fold`).
- **No compatibility ids.** No `CompatibleSchemaIds` on any renamed type. An
Eve-typed store is deleted and rebuilt by its daemon, conformance packs are
re-exported under thing ids, and a store found to be truth stops its cut as a
fork (`thing:ruling:operator-compat-rebuild`). A port therefore carries a
rebuild step, not a reader of old ids.
- **No new Eve surfaces.** Thing, formerly Eve, is deprecated; every new surface
waits for Thing 2.0 (`thing2:ruling:surfaces-wait-for-thing2`). Operator
dashboards are quarantined (parked tag, removed from main and the build) and
rebuilt on Thing 2 by follow-ups, e.g. `thing2:follow_up:ymir-operator-view-on-thing2`,
`weksa-`, `mimir-`, `muninn-operator-view-on-thing2`
(`thing2:ruling:eve-dashboards-quarantined-2`). Product UIs are decided case by
case: `Mimir.EveSensorReceiver` and the Pitch page's visual-novel component are
frozen until Thing 2, neither extended nor removed
(`thing2:ruling:mimir-sensor-receiver-frozen`, `thing2:ruling:pitch-component-frozen`).
- **Discovery is not Thing's.** A port reads the provider advertisement through the
`thing-mesh` port, not through a Thing-owned kind (`thing2:ruling:advertisement-owner`).
Until the owner lands (`thing2:follow_up:discovery-owner-campaign`), one adapter
over today's `gamecult.eve.provider_advertisement.v1` serves the port and is
deleted when the owner's typed advertisement arrives.
- **Repo set.** The code home is the Eve repo renamed Thing; Unity and Flutter
backends get their own repos only when a live consumer needs one
(`thing2:ruling:code-home`). The campaign waits for `cut-campaign-repos`, then
target r2 names the 13 repos before the first port
(`thing2:ruling:campaign-repo-limit`). The six retired family repos are archived
under their Eve names (`thing2:ruling:retired-repo-names`).
**Port-list gap.** gamecult-site's Thing 1 surface is tracked in
`void-body:follow_up:site-eve-present-tense` (Void's mind; folded there by
`thing2:resolution:follow_up.site-thing1-surface.n1`), and its Pitch component is
frozen until Thing 2 (`thing2:ruling:pitch-component-frozen`). The repo count
stays 13.
The template (every port cut has the same spec skeleton, so Soul can run the same
falsifications):
1. Fixture first: the consumer's current surface rebuilt as a Thing Script document
through its language package, loaded into `thing-testkit`, geometry-golden'd.
2. Deletes: its Thing 1 publisher path and every `gamecult.eve.*` reader/writer
(exact paths from the census, to `file:line`).
3. Commands: each existing command becomes a `CommandDecl` and a handler
returning an `Outcome` through the package (no state-as-string, M3).
4. Test: the consumer's own suite plus one pipeline smoke that renders the
consumer's real surface headlessly through core and asserts the geometry golden
and the command round-trip. Operator check: view it in the TUI/web.
5. Negative grep: no `gamecult.eve` and no `eve-browser-lowering` imports remain.
- **Prior art:** expand/contract (parallel change) and strangler-fig, with the
caveat in R-K §4 that Thing 2 kinds are new kinds not renames, so an aggregator
reads two kinds, not one under two ids **[read]**. Confidence high on the
template, per-consumer specs owe their own census read.
### Piece 14: retirement
Delete Thing 1's tree from the kernel repo after the last port. Test: negative
greps for `gamecult.eve`, `eve-browser-lowering`, `packages/eve-contracts`,
`web/eve-dsl.js`; workspace builds with the directories gone; README front door
(`doctrine`: first screen true) rewritten; Idunn targets (P15) re-pointed. Soul
pass before the tag.
## 4. What every cut's Soul pass attacks (derived, not new)
Rules M1-M10 are the checklist; in addition the shared failure shapes from this
spec: (i) a backend that grows layout, text or focus (compare dependency trees and
public fns); (ii) a decode refusal that reads as absence; (iii) a rule held by a
constructor but skipped by decode (the contract's P18 lesson, now applied to
`CommandInvocation` and results received by core); (iv) a golden re-blessed to
match a bug (Soul reruns generation on a clean checkout and diffs); (v) an `Embed`
or placeholder that silently drops.
## 5. Decisions made here (summary)
| ID | Decision | Confidence |
| --- | --- | --- |
| D1 | One `thing-core` crate with modules; six crates in total | medium-high |
| D2 | Nine-variant closed render-command list | medium |
| D3 | Closed diagnostics enum drives placeholders, logs, a11y and tests | high |
| D4 | Byte-compared binary render and geometry goldens, `bless` task | medium |
| D5 | Invocation lifecycle with core-only `Malformed` and `TimedOut` | medium-high |
| D6 | Cell widths pinned to a `unicode-width` version in goldens | medium |
| D7 | One focus owner in core, id-keyed, modal trap | medium-high |
| D8 | (see O7) edit history scope | open |
| D9 | Web draws through canvas 2D first | medium |
## 6. Open: what this spec could not decide
Each with a recommendation; none blocks cuts 1-8.
- **O1. Parley (and AccessKit types) on `wasm32`.** No source read establishes
that Parley + fontique build and perform for wasm; GPUI web has its own text
system and Slint web uses femtovg, not Parley. Recommendation: one half-day
probe (build `thing-core` text module to wasm, shape `f12`) before cut 9a is
specced; the fallback is browser `Canvas.measureText` behind the `Measure` trait,
which weakens "core owns text" for the web only. `thing:ruling:thing2-thing-owns-text`
already puts shaping in core, so taking the fallback contradicts it and needs a
new operator ruling. Needs: the probe.
- **O2. Glyph rasterization path** (canvas 2D, Slug, Vello family). Partly ruled:
rasterization is backend-private and the first GPU backend picks Vello or a Slug
port by measurement (`thing:ruling:thing2-thing-owns-text`). Still open:
Recommendation: canvas 2D now; revisit after a measured frame budget (O10).
Needs: operator word on whether GPU glyphs gate web cutover.
- **O3. The exact command list**, in particular whether `Plot` lowers to
`Polyline`/`Polygon` in core or becomes an `Embed`. Recommendation: lower in core
(consumers expect charts; an `Embed` makes every host write one). Needs: a
decision on D2 from the spec's reviewer.
- **O4. CultMesh/CultNet surface for `thing-mesh` and how a browser reaches it**
(direct WebTransport/QUIC, or a gateway). Not read in this pass. Who owns the
provider advertisement is ruled (`thing2:ruling:advertisement-owner`: discovery
leaves Thing, its owner is CultMesh or Odin, follow-up
`thing2:follow_up:discovery-owner-campaign`); the transport question stays open.
Needs: a short
Eyes pass over `cultmesh-ts`/`cultnet-ts` in CultLib before cut 12 and 11c are
specced.
- **O5. Defaults that are guesses:** invocation timeout 15 s, frame budget, scrollbar
style, overlay z policy. Recommendation: land as `Config` with these defaults and
record a follow-up to measure.
- **O6. What only the operator can check:** real IME on Windows/macOS/iOS/Android
browsers, a real screen reader on the web mirror. No CI substitute exists; the
spec names them as operator checks at cut 11 and at each consumer cutover.
- **O7. Editing scope (D8):** undo/redo, clipboard, drag-select auto-scroll in 9b.
Recommendation: undo and clipboard are in (a general library's reasonable
expectation; clipboard goes through `HostEffects`), word/line navigation in,
rich text out. Needs: nothing but a go.
- **O8. Locale in `Format`.** Recommendation: a host-supplied `Locale` input,
default `en`, formats stay a closed set.
- **O9. Diagnostics added by later cuts** (`AssetMissing`, `NoAccessibleName`)
extend D3's list; confirm the list stays closed and versioned with core.
- **O10. Performance budgets** (frame time at 1k and 10k nodes, wasm size). No
number was measured anywhere in the sources read; Clay's "microsecond layout"
claim has no table (R-F §2.1) and the Taffy README numbers are layout-only
(R-F §2.2). Recommendation: cut 6 records the first measured numbers in a
bench fixture, and budgets are set from them rather than guessed.
- **O11. Thing Script text syntax: closed by ruling, no open question.**
`thing2:ruling:thing-script-form` (InForce, ruled 2026-10-10, choice
`document-authority-text-later`; operator: "all recommended") says the typed
document is Thing Script's one authority, and a `.thingscript` text syntax comes
later, parsed only by core. Consequences held in this spec: nothing but the typed
document is authoritative; no language package or host parses a text form (packages
build the typed document and nothing else; tooling reaches the one parser through core, which
the question's recommendation expects to expose via wasm); when the text form is cut
it lands in `thing-core` next to `resolve` and produces a `SurfaceDocument`, so
`resolve` still sees only the typed document, and its tests are round-trip
(text to document to text) plus the existing `resolve` suite on the parsed
output. It has no cut yet and sits after cut 3; the map's cut order is not
changed here.
- **O12. Prior-art standard.** This spec reads "prior-art sources cited" as: every
decision names the sources and a confidence, with [read]/[background] honesty.
Open: whether the standard also fixes a format, a minimum source count or a
required venue; the tags above are where to retrofit it.
- **O13. Where the repo's unmerged contract-ts / contract-cs branches stand.**
Ruled as far as the mind records: the live specs are `cut-contract-ts.r3` and
`-cs.r3`, which wait on contract-cs h2 being admitted, held by Soul and merged
by Self. This spec did not re-verify branch heads; that check belongs to the
merging Self.
## 7. Substrate gaps felt writing this spec
- Resolved: the `thing2` and `thing` campaigns are now readable
(`huginn rulings thing2 thing`, `huginn view <id>`), and this spec was checked
against them on 2026-11-10. Rulings are now cited by id. Remaining gap: the
`huginn rulings` header line truncates the choice, so each ruling needs a `view`.
- No published golden-command suite exists to copy (D4); the harness is ours to
build and is itself a cut-1 testkit deliverable.

View file

@ -22,7 +22,7 @@ restate their options. Research for the forks:
## Body facts ## Body facts
Probes P1-P16 ran 2026-10-10, P17-P19 2026-10-12, against `origin/<default>` after `git fetch` unless a Probes P1-P16 ran 2026-10-10, P17-P22 2026-10-12, against `origin/<default>` after `git fetch` unless a
local path is named. Scripts are in the session scratchpad local path is named. Scripts are in the session scratchpad
`imagination-thing2-contract/`. `imagination-thing2-contract/`.
@ -206,6 +206,75 @@ records are rebuilt, not read (`thing:ruling:operator-compat-rebuild`), so the
Thing 2.0 key grammar strands nothing. Probe evidence of the collision itself: Thing 2.0 key grammar strands nothing. Probe evidence of the collision itself:
Soul's `soul-thing2-contract-rs/rust1.log` KEY lines. Soul's `soul-thing2-contract-rs/rust1.log` KEY lines.
**P20. In C#, the constructor MessagePack calls is the one door, and the decode
recursion fits a default thread inside the bound.** Probe
`imagination-contract-cs-ts/` (throwaway commit `e5030d3b` on CultLib
`b3bd8dd5`, Yggdrasil, image dotnet sdk 10.0, MessagePack 3.1.7, Debug and
Release, log `cs2.log`). A `[MessagePackObject]` class with get-only `[Key]`
properties and one constructor taking the keys in slot order, throwing on
`seq < 1`:
- public constructor: `CultDocumentRegistry` accepts it; `result-pending.bin`
decodes through `CultDocumentMessagePackSerialization` and re-encodes
identical; `result-seq-zero.bin` is refused by the constructor through
`DeserializeUntyped`, through `MessagePackSerializerOptions.Standard`, and
through `System.Text.Json` (which calls the same constructor); no message
holds the golden's canary.
- private constructor with `[SerializationConstructor]` under
`[MessagePackObject(AllowPrivate = true)]`: the same results, the registry
accepts it, reflection finds no public constructor and no public setter, and
`System.Text.Json` refuses the type (`NotSupportedException`).
- internal constructor without `AllowPrivate`: the registry refuses the type
("no constructor MessagePack can call"), and `CultDocumentRegistry.Shared`
then refuses every type in the assembly, so one bad type breaks the package.
- `outcome-unknown-arm.bin` is refused through `CultDocumentMessagePackSerialization`
(`CultUnionGuard`: "Union ... has no arm for key 4"), but decodes with a null
outcome through `MessagePackSerializerOptions.Standard`: the guard lives only
in CultLib's options, so a package decodes only through them.
- Stack: a Box-shaped recursive union (3 containers per level) reaches the
256 bound at 84 levels. Decoding recurses per level: depth 10 decodes on a
64 KiB thread, depth 84 needs 256 KiB in Debug and 128 KiB in Release, and an
overflow aborts the process (rc 134). .NET's 1 MiB default thread holds the
deepest admitted payload with at least 4x margin, so C# carries no part of
`cultlib-gaps:follow_up:decode-stack-safety`.
**P21. In TypeScript, cultcache-ts runs a document's codec and schema on both
doors, and its recursion fits the default stack.** Same probe commit, image
kotlin (Node 24.21.0), log `ts2.log`. cultcache-ts at `b3bd8dd5` (0.14.0) has
`slots`, `union`, `list`, `lazy`, `unit` and the 256 payload bound;
`decodeDocumentPayload` runs the codec then `schema.parse`, and
`encodeDocumentPayload` runs `schema.parse` then the codec
(`src/document.ts`). A `seq` codec delegating to `int32` with a `>= 1` check,
and a `CommandResult` class with a `#brand` private field, a private
constructor, a codec wrapping its slot codec that mints an instance on decode,
and a `schema.parse` that refuses anything without the brand:
- `result-pending.bin` decodes to an instance and re-encodes identical;
`result-seq-zero.bin` is refused ("seq (slot 1): Seq must be at least 1");
`outcome-unknown-arm.bin` is refused ("Union Outcome: unknown arm key 4");
`result-extra-slot.bin` reads as seq 1; no message holds the canary.
- `structuredClone`, spread and `JSON.parse` of an instance lose the brand,
and encoding any of them, or an object literal with seq 0, is refused; the
factory with seq 0 throws.
- `tsc` (strict, NodeNext, ESM importing the CommonJS cultcache-ts) passes
with `@ts-expect-error` on an object literal and a spread typed
`CommandResult`, on `new CommandResult(...)`, and on assigning `seq`;
`structuredClone(result)` and `JSON.parse` still type as `CommandResult`, so
the runtime brand check is the guard there.
- Stack: the same chain reaches the bound at 84 levels. Depth 84 decodes with
`--stack-size` 200 and the default 984; at 60 to 120 the codec throws (a
`RangeError`, wrapped by the codec into its own refusal), never aborting.
**P22. Packaging around the two packages.** Eve `6ae2da0`: `.gitignore`
ignores `packages/*` with one `!` pair per package (lines 2-16), so a new
package directory is invisible to git until it gets its pair, and global
`obj/` (line 17) is where the Thing 1 test project keeps its output
(`BaseOutputPath obj\bin\`). `GameCult.Eve.Surface.csproj` reads CultLib from
`CultLibRoot`, defaulting to the sibling checkout `..\..\..\CultLib`.
`npm view @gamecult/cultcache-ts` answers 404: cultcache-ts is on no registry,
and the consumers that use it (Heimdall, StreamPixels) take it as
`file:vendor/CultLib/packages/cultcache-ts` from a submodule. No file outside
`crates/` and `docs/` names `thing-contract` or `GameCult.Thing.Contract` at
`6ae2da0` except `Cargo.lock`.
## The model page ## The model page
Every persistent kind Thing 2.0 has. Ids follow rename table T: schema Every persistent kind Thing 2.0 has. Ids follow rename table T: schema
@ -404,6 +473,10 @@ code fails it.
## Cut order (deliverables) ## Cut order (deliverables)
Per-piece contracts, the build graph with sizes, a test per piece and the prior-art
citations for each choice are in `docs/thing2-build-spec.md`; this list is the
summary.
0. **`stale-voidbot-cleanup`** (Eve main, any time): spec 0. **`stale-voidbot-cleanup`** (Eve main, any time): spec
`thing2:cut_spec:cut-stale-voidbot-cleanup.r1`. Owned here by `thing2:cut_spec:cut-stale-voidbot-cleanup.r1`. Owned here by
`thing:follow_up:stale-voidbot-cleanup-on-main`. `thing:follow_up:stale-voidbot-cleanup-on-main`.
@ -413,22 +486,31 @@ code fails it.
consumers' languages: Rust, JS/TS, C#). The first proof (P9) was run: a consumers' languages: Rust, JS/TS, C#). The first proof (P9) was run: a
Rust-written recursive union does not decode in the C# reference, nor the Rust-written recursive union does not decode in the C# reference, nor the
reverse (P12), and TS decodes only what a hand-written codec says (P13). The reverse (P12), and TS decodes only what a hand-written codec says (P13). The
contract waits on CultLib's union parity contract waited on CultLib's union parity
(`thing2:follow_up:cultcache-union-parity`). Three cuts: `contract-rs`, then (`thing2:follow_up:cultcache-union-parity`), which is on CultLib main by
`b3bd8dd5` (P20, P21) and unreleased. Three cuts: `contract-rs`, then
`contract-ts` and `contract-cs`. The published schema of each kind is its `contract-ts` and `contract-cs`. The published schema of each kind is its
CultCache catalog entry, identical in the three packages; no JSON Schema CultCache catalog entry, identical in the three packages; no JSON Schema
files are written, because Thing 2.0 has no JSON reader of these kinds (the files are written, because Thing 2.0 has no JSON reader of these kinds (the
browser reads them through core, not `ajv`). Python and Kotlin packages browser reads them through core, not `ajv`). Python and Kotlin packages
follow as their own deliverables. follow as their own deliverables.
`contract-rs` attempt 1 landed on `hands/thing2-contract-rs` (`649844aa`); `contract-rs` landed on Eve main (`6ae2da0`) after two Soul passes
Soul's `thing2:verdict:cut-contract-rs.s1` returned seven findings. Its fix (`thing2:verdict:cut-contract-rs.s1`, `.s2`). The siblings are mapped
batch is `thing2:cut_spec:cut-contract-rs.r2`. Waiting, one line each: against `6ae2da0` and run side by side, touching only their own package and
- `contract-ts`, `contract-cs`: their r1 specs predate r2's domain types, one `.gitignore` insertion each, at separate anchors:
key grammar and refusal goldens, and are refreshed when the frontier `thing2:cut_spec:cut-contract-cs.r3` and `thing2:cut_spec:cut-contract-ts.r3`.
reaches them. Waiting, one line each:
- CultLib pin bump: when `cultlib-gaps:follow_up:decode-stack-safety` lands, - Cross-runtime store check, after both siblings land: the C# package opens
move the pin and run `deep_tree` on the default thread (its 16 MiB thread a store the TS package wrote and the reverse, which proves the catalog
goes); the crate docs' hazard note goes with it. type names (`GameCult.Thing.Contract.<RustName>`) agree; neither sibling
can prove it alone.
- Publication: when `cultlib-gaps:cut_spec:cut-union-parity-release.r3`
publishes cultcache-ts, the TS package's dependency moves from the sibling
`file:` path to the published version, and both packages get a release
line. Until then both read CultLib from the sibling checkout at the Cargo
rev (P22).
- CultLib pin bump: done at CultLib `4c9af401` (cut bind-pin); `deep_tree`
runs on the default thread and the crate docs' hazard note is gone.
- Missing-slot golden: re-added only when - Missing-slot golden: re-added only when
`cultlib-gaps:follow_up:rust-missing-slot-vs-reference` settles the rule. `cultlib-gaps:follow_up:rust-missing-slot-vs-reference` settles the rule.
2. **Core**, in three cuts: (a) resolution, compositions with `thing.std`, 2. **Core**, in three cuts: (a) resolution, compositions with `thing.std`,
@ -505,6 +587,23 @@ have no live consumer and are parked until one appears.
instead impose a grammar on ids the contract does not own. Listing a instead impose a grammar on ids the contract does not own. Listing a
provider's records filters on the record's provider field, not a key prefix, provider's records filters on the record's provider field, not a key prefix,
because a dotted provider is a prefix of a longer one. because a dotted provider is a prefix of a longer one.
- **Why each sibling holds its domains where its decoder constructs.** The
rule from contract-rs is that a domain is checked on every door by one owner.
C# has no newtype that keeps the leaf's bytes without a custom formatter,
which CultLib owns, but MessagePack, System.Text.Json and code all build a
C# value through the one constructor that takes the slots (P20), so that
constructor, calling `ThingDomain`, is the door. cultcache-ts runs each
slot's codec on encode and decode (P21), so a domain codec over the plain
leaf is the door there, the same shape as Rust's newtype `Deserialize`.
`CommandResult` is closed differently in each language: a private
constructor under `AllowPrivate` in C#, a `#brand` field checked by the
document's `schema.parse` in TS, because TypeScript's structural types let
any object with the right fields pass as a class with only public members.
- **Why the siblings read CultLib from a sibling checkout, not a submodule.**
The C# package already reads CultLib that way (`CultLibRoot`), cultcache-ts
is on no registry yet (P22), and the Rust crate pins the same commit by
Cargo rev. A submodule would be a third pin to keep equal to the Cargo rev;
publication replaces the `file:` path instead.
- **Why contract-rs merges before CultLib's stack fix.** The overflow is the - **Why contract-rs merges before CultLib's stack fix.** The overflow is the
decode door's (`cultlib-gaps:follow_up:decode-stack-safety`) and every Rust decode door's (`cultlib-gaps:follow_up:decode-stack-safety`) and every Rust
reader of these kinds inherits it whether or not the contract merges. The reader of these kinds inherits it whether or not the contract merges. The

View file

@ -0,0 +1,45 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using GameCult.Caching;
using MessagePack;
namespace GameCult.Thing.Contract;
[MessagePackObject]
public sealed class AssetEntry
{
[Key(0)] public string Id { get; }
[Key(1)] public string MediaType { get; }
[Key(2)] public string Uri { get; }
[Key(3)] public int Width { get; }
[Key(4)] public int Height { get; }
public AssetEntry(string id, string mediaType, string uri, int width, int height)
{
Id = ThingDomain.Present(id, "Id");
MediaType = ThingDomain.Present(mediaType, "MediaType");
Uri = ThingDomain.Present(uri, "Uri");
Width = ThingDomain.Count(width);
Height = ThingDomain.Count(height);
}
}
[CultDocument("gamecult.thing.asset_catalog", "gamecult.thing.asset_catalog.v1")]
[MessagePackObject]
public sealed class AssetCatalog
{
[Key(0)] public string ProviderId { get; }
[Key(1)] public string CatalogId { get; }
[Key(2)] public long Version { get; }
[Key(3)] public ImmutableArray<AssetEntry> Assets { get; }
public AssetCatalog(string providerId, string catalogId, long version, IReadOnlyList<AssetEntry> assets)
{
ProviderId = ThingDomain.Present(providerId, "ProviderId");
CatalogId = ThingDomain.Segment(catalogId);
Version = ThingDomain.Version(version);
Assets = ThingDomain.Items(assets, "Assets");
}
[IgnoreMember] public string RecordKey => ThingKeys.AssetCatalogKey(ProviderId, CatalogId);
}

View file

@ -0,0 +1,178 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using GameCult.Caching;
using MessagePack;
namespace GameCult.Thing.Contract;
[Union(0, typeof(CommandIdRef))]
[Union(1, typeof(CommandRefParam))]
public abstract class CommandRef
{
internal CommandRef() { }
}
[MessagePackObject]
public sealed class CommandIdRef : CommandRef
{
[Key(0)] public string Id { get; }
public CommandIdRef(string id)
{
Id = ThingDomain.Present(id, "Id");
}
}
[MessagePackObject]
public sealed class CommandRefParam : CommandRef
{
[Key(0)] public string Name { get; }
public CommandRefParam(string name)
{
Name = ThingDomain.Present(name, "Name");
}
}
[Union(0, typeof(TextValue))]
[Union(1, typeof(NumberValue))]
[Union(2, typeof(BoolValue))]
[Union(3, typeof(ChoiceValue))]
public abstract class InputValue
{
internal InputValue() { }
}
[MessagePackObject]
public sealed class TextValue : InputValue
{
[Key(0)] public string Value { get; }
public TextValue(string value)
{
Value = ThingDomain.Present(value, "Value");
}
}
[MessagePackObject]
public sealed class NumberValue : InputValue
{
[Key(0)] public double Value { get; }
public NumberValue(double value)
{
Value = value;
}
}
[MessagePackObject]
public sealed class BoolValue : InputValue
{
[Key(0)] public bool Value { get; }
public BoolValue(bool value)
{
Value = value;
}
}
[MessagePackObject]
public sealed class ChoiceValue : InputValue
{
[Key(0)] public string Value { get; }
public ChoiceValue(string value)
{
Value = ThingDomain.Present(value, "Value");
}
}
[MessagePackObject]
public sealed class CommandDecl
{
[Key(0)] public string Id { get; }
[Key(1)] public string PayloadSchema { get; }
[Key(2)] public ImmutableArray<string> Captures { get; }
[Key(3)] public string? Confirm { get; }
public CommandDecl(string id, string payloadSchema, IReadOnlyList<string> captures, string? confirm)
{
Id = ThingDomain.Present(id, "Id");
PayloadSchema = ThingDomain.Present(payloadSchema, "PayloadSchema");
Captures = ThingDomain.Items(captures, "Captures");
Confirm = confirm;
}
}
/// <summary>
/// A typed record as its MessagePack bytes. Every empty memory (<c>ReadOnlyMemory&lt;byte&gt;.Empty</c>, a default view,
/// an empty array) is an empty payload, as Rust's empty <c>Vec&lt;u8&gt;</c> is. A nil on the wire is not an empty
/// payload: it decodes to a default view the constructor cannot tell from an empty one, so the constructor notes it and
/// the decode door refuses it once the value is read.
/// </summary>
[MessagePackObject]
public sealed class RecordPayload : IMessagePackSerializationCallbackReceiver
{
private readonly bool _viewWasDefault;
[Key(0)] public string Schema { get; }
[Key(1)] public ReadOnlyMemory<byte> Bytes { get; }
public RecordPayload(string schema, ReadOnlyMemory<byte> bytes)
{
Schema = ThingDomain.Present(schema, "Schema");
_viewWasDefault = bytes.Equals(default(ReadOnlyMemory<byte>));
Bytes = bytes.ToArray();
}
void IMessagePackSerializationCallbackReceiver.OnBeforeSerialize() { }
void IMessagePackSerializationCallbackReceiver.OnAfterDeserialize()
{
if (_viewWasDefault) throw new ThingDomainException("Bytes", "present");
}
}
[MessagePackObject]
public sealed class CapturedInput
{
[Key(0)] public string Node { get; }
[Key(1)] public InputValue Value { get; }
public CapturedInput(string node, InputValue value)
{
Node = ThingDomain.Present(node, "Node");
Value = ThingDomain.Present(value, "Value");
}
}
[CultDocument("gamecult.thing.command_invocation", "gamecult.thing.command_invocation.v1")]
[MessagePackObject]
public sealed class CommandInvocation
{
[Key(0)] public string InvocationId { get; }
[Key(1)] public string SurfaceKey { get; }
[Key(2)] public long SurfaceVersion { get; }
[Key(3)] public string Command { get; }
[Key(4)] public RecordPayload Payload { get; }
[Key(5)] public ImmutableArray<CapturedInput> Captured { get; }
[Key(6)] public string Client { get; }
[Key(7)] public string IssuedAt { get; }
[Key(8)] public string? Delegation { get; }
public CommandInvocation(string invocationId, string surfaceKey, long surfaceVersion, string command, RecordPayload payload, IReadOnlyList<CapturedInput> captured, string client, string issuedAt, string? delegation)
{
InvocationId = ThingDomain.Present(invocationId, "InvocationId");
SurfaceKey = ThingDomain.Present(surfaceKey, "SurfaceKey");
SurfaceVersion = ThingDomain.Version(surfaceVersion);
Command = ThingDomain.Present(command, "Command");
Payload = ThingDomain.Present(payload, "Payload");
Captured = ThingDomain.Items(captured, "Captured");
Client = ThingDomain.Present(client, "Client");
IssuedAt = ThingDomain.Present(issuedAt, "IssuedAt");
Delegation = delegation;
}
[IgnoreMember] public string RecordKey => ThingKeys.InvocationKey(InvocationId);
}

View file

@ -0,0 +1,64 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
namespace GameCult.Thing.Contract;
/// <summary>A value was outside its domain. Names the domain and its bound, never the value.</summary>
public sealed class ThingDomainException : Exception
{
public ThingDomainException(string domain, string bound) : base($"{domain} must be {bound}")
{
Domain = domain;
Bound = bound;
}
/// <summary>The domain that refused.</summary>
public string Domain { get; }
/// <summary>The bound that was not met.</summary>
public string Bound { get; }
}
/// <summary>
/// The value domains of the contract's numbers, local names and slots. A required slot is never null, and a list is a
/// private copy that holds no nil item. Every constructor whose field carries a domain calls the
/// matching check, and every deserializer reaches a value through that constructor, so no door skips a check.
/// </summary>
public static class ThingDomain
{
/// <summary>A result's position in its invocation's answers, counting from 1.</summary>
public static int Seq(int value) => value >= 1 ? value : throw new ThingDomainException("Seq", "at least 1");
/// <summary>A document or source version, never negative.</summary>
public static long Version(long value) => value >= 0 ? value : throw new ThingDomainException("Version", "at least 0");
public static long? Version(long? value) => value.HasValue ? Version(value.Value) : null;
/// <summary>A count, an extent or an index, never negative.</summary>
public static int Count(int value) => value >= 0 ? value : throw new ThingDomainException("Count", "at least 0");
public static int? Count(int? value) => value.HasValue ? Count(value.Value) : null;
/// <summary>A name the contract joins into a key: non-empty, no '.'.</summary>
public static string Segment(string value) =>
string.IsNullOrEmpty(value) ? throw new ThingDomainException("Segment", "non-empty")
: value.IndexOf('.') >= 0 ? throw new ThingDomainException("Segment", "free of '.'")
: value;
/// <summary>A required slot: the value, or a refusal naming the slot when it is null.</summary>
public static T Present<T>(T? value, string slot) where T : class =>
value ?? throw new ThingDomainException(slot, "present");
/// <summary>
/// A required list slot, as a whole-value holder: a copy, so the caller's list cannot change the value afterwards.
/// A null list, a default array (what a nil payload decodes to) or a null item is refused naming the slot.
/// </summary>
public static ImmutableArray<T> Items<T>(IReadOnlyList<T>? items, string slot) where T : class
{
if (items is null || items is ImmutableArray<T> { IsDefault: true }) throw new ThingDomainException(slot, "present");
var builder = ImmutableArray.CreateBuilder<T>(items.Count);
foreach (var item in items) builder.Add(item ?? throw new ThingDomainException(slot, "free of nil items"));
return builder.MoveToImmutable();
}
}

View file

@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<Nullable>enable</Nullable>
<LangVersion>latest</LangVersion>
<Description>The gamecult.thing.* wire types, held to the Rust crate's goldens.</Description>
<PackageId>GameCult.Thing.Contract</PackageId>
<Version>0.1.0</Version>
<Authors>GameCult</Authors>
<PackageLicenseExpression>MPL-2.0</PackageLicenseExpression>
<PackageProjectUrl>https://github.com/GameCult/Eve</PackageProjectUrl>
<RepositoryUrl>https://github.com/GameCult/Eve</RepositoryUrl>
<BaseOutputPath>obj\bin\</BaseOutputPath>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<NoWarn>$(NoWarn);CS1591</NoWarn>
<CultLibRoot Condition="'$(CultLibRoot)' == ''">$(MSBuildThisFileDirectory)..\..\..\CultLib</CultLibRoot>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="$(CultLibRoot)\src\GameCult.Caching\GameCult.Caching.csproj" />
<PackageReference Include="System.Collections.Immutable" Version="8.0.0" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,25 @@
using System.Globalization;
namespace GameCult.Thing.Contract;
/// <summary>
/// The key of each kind. Each key joins free-string provider or publisher ids (dotted, as the Verse names them)
/// with typed trailing parts: a segment holds no dot and a seq or version is digits, so a key splits at its last dot
/// (surface, asset catalog, result) or last two (composition), and two different field sets never build one key.
/// </summary>
public static class ThingKeys
{
public static string SurfaceKey(string providerId, string label) =>
$"thing:surface:{ThingDomain.Present(providerId, "ProviderId")}.{ThingDomain.Segment(label)}";
public static string CompositionKey(string publisher, string name, long version) =>
$"thing:composition:{ThingDomain.Present(publisher, "Publisher")}.{ThingDomain.Segment(name)}.v{ThingDomain.Version(version).ToString(CultureInfo.InvariantCulture)}";
public static string InvocationKey(string invocationId) => $"thing:invocation:{ThingDomain.Present(invocationId, "InvocationId")}";
public static string ResultKey(string invocationId, int seq) =>
$"thing:result:{ThingDomain.Present(invocationId, "InvocationId")}.{ThingDomain.Seq(seq).ToString(CultureInfo.InvariantCulture)}";
public static string AssetCatalogKey(string providerId, string catalogId) =>
$"thing:asset_catalog:{ThingDomain.Present(providerId, "ProviderId")}.{ThingDomain.Segment(catalogId)}";
}

View file

@ -0,0 +1,681 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using GameCult.Caching;
using MessagePack;
namespace GameCult.Thing.Contract;
[Union(0, typeof(BoxNode))]
[Union(1, typeof(TextNode))]
[Union(2, typeof(ImageNode))]
[Union(3, typeof(ButtonNode))]
[Union(4, typeof(ToggleNode))]
[Union(5, typeof(SliderNode))]
[Union(6, typeof(TextInputNode))]
[Union(7, typeof(SelectNode))]
[Union(8, typeof(RepeatNode))]
[Union(9, typeof(OverlayNode))]
[Union(10, typeof(PlotNode))]
[Union(11, typeof(EmbedNode))]
[Union(12, typeof(UseNode))]
[Union(13, typeof(SlotNode))]
public abstract class Node
{
internal Node() { }
}
[MessagePackObject]
public sealed class BoxNode : Node
{
[Key(0)] public NodeCommon Common { get; }
[Key(1)] public BoxStyle Style { get; }
[Key(2)] public Paint Paint { get; }
[Key(3)] public Role Role { get; }
[Key(4)] public ImmutableArray<Node> Children { get; }
public BoxNode(NodeCommon common, BoxStyle style, Paint paint, Role role, IReadOnlyList<Node> children)
{
Common = ThingDomain.Present(common, "Common");
Style = ThingDomain.Present(style, "Style");
Paint = ThingDomain.Present(paint, "Paint");
Role = ThingDomain.Present(role, "Role");
Children = ThingDomain.Items(children, "Children");
}
}
[MessagePackObject]
public sealed class TextNode : Node
{
[Key(0)] public NodeCommon Common { get; }
[Key(1)] public TextSource Content { get; }
[Key(2)] public string StyleToken { get; }
[Key(3)] public bool Wrap { get; }
[Key(4)] public int? MaxLines { get; }
[Key(5)] public bool Selectable { get; }
public TextNode(NodeCommon common, TextSource content, string styleToken, bool wrap, int? maxLines, bool selectable)
{
Common = ThingDomain.Present(common, "Common");
Content = ThingDomain.Present(content, "Content");
StyleToken = ThingDomain.Present(styleToken, "StyleToken");
Wrap = wrap;
MaxLines = ThingDomain.Count(maxLines);
Selectable = selectable;
}
}
[MessagePackObject]
public sealed class ImageNode : Node
{
[Key(0)] public NodeCommon Common { get; }
[Key(1)] public string Catalog { get; }
[Key(2)] public string Asset { get; }
[Key(3)] public ImageFit Fit { get; }
[Key(4)] public TextSource Alt { get; }
public ImageNode(NodeCommon common, string catalog, string asset, ImageFit fit, TextSource alt)
{
Common = ThingDomain.Present(common, "Common");
Catalog = ThingDomain.Present(catalog, "Catalog");
Asset = ThingDomain.Present(asset, "Asset");
Fit = ThingDomain.Present(fit, "Fit");
Alt = ThingDomain.Present(alt, "Alt");
}
}
[MessagePackObject]
public sealed class ButtonNode : Node
{
[Key(0)] public NodeCommon Common { get; }
[Key(1)] public ImmutableArray<Node> Content { get; }
[Key(2)] public CommandRef OnActivate { get; }
[Key(3)] public BoolSource Enabled { get; }
public ButtonNode(NodeCommon common, IReadOnlyList<Node> content, CommandRef onActivate, BoolSource enabled)
{
Common = ThingDomain.Present(common, "Common");
Content = ThingDomain.Items(content, "Content");
OnActivate = ThingDomain.Present(onActivate, "OnActivate");
Enabled = ThingDomain.Present(enabled, "Enabled");
}
}
[MessagePackObject]
public sealed class ToggleNode : Node
{
[Key(0)] public NodeCommon Common { get; }
[Key(1)] public BoolSource Checked { get; }
[Key(2)] public CommandRef OnChange { get; }
public ToggleNode(NodeCommon common, BoolSource @checked, CommandRef onChange)
{
Common = ThingDomain.Present(common, "Common");
Checked = ThingDomain.Present(@checked, "Checked");
OnChange = ThingDomain.Present(onChange, "OnChange");
}
}
[MessagePackObject]
public sealed class SliderNode : Node
{
[Key(0)] public NodeCommon Common { get; }
[Key(1)] public double Min { get; }
[Key(2)] public double Max { get; }
[Key(3)] public double Step { get; }
[Key(4)] public NumberSource Value { get; }
[Key(5)] public CommandRef Commit { get; }
public SliderNode(NodeCommon common, double min, double max, double step, NumberSource value, CommandRef commit)
{
Common = ThingDomain.Present(common, "Common");
Min = min;
Max = max;
Step = step;
Value = ThingDomain.Present(value, "Value");
Commit = ThingDomain.Present(commit, "Commit");
}
}
[MessagePackObject]
public sealed class TextInputNode : Node
{
[Key(0)] public NodeCommon Common { get; }
[Key(1)] public bool Multiline { get; }
[Key(2)] public InputKind InputKind { get; }
[Key(3)] public TextSource Placeholder { get; }
[Key(4)] public TextSource Initial { get; }
[Key(5)] public CommandRef Submit { get; }
public TextInputNode(NodeCommon common, bool multiline, InputKind inputKind, TextSource placeholder, TextSource initial, CommandRef submit)
{
Common = ThingDomain.Present(common, "Common");
Multiline = multiline;
InputKind = ThingDomain.Present(inputKind, "InputKind");
Placeholder = ThingDomain.Present(placeholder, "Placeholder");
Initial = ThingDomain.Present(initial, "Initial");
Submit = ThingDomain.Present(submit, "Submit");
}
}
[MessagePackObject]
public sealed class SelectNode : Node
{
[Key(0)] public NodeCommon Common { get; }
[Key(1)] public OptionList Options { get; }
[Key(2)] public Bind Value { get; }
[Key(3)] public CommandRef OnChange { get; }
public SelectNode(NodeCommon common, OptionList options, Bind value, CommandRef onChange)
{
Common = ThingDomain.Present(common, "Common");
Options = ThingDomain.Present(options, "Options");
Value = ThingDomain.Present(value, "Value");
OnChange = ThingDomain.Present(onChange, "OnChange");
}
}
[MessagePackObject]
public sealed class RepeatNode : Node
{
[Key(0)] public NodeCommon Common { get; }
[Key(1)] public CollectionSource Collection { get; }
[Key(2)] public MemberPath KeyMember { get; }
[Key(3)] public Node Template { get; }
public RepeatNode(NodeCommon common, CollectionSource collection, MemberPath keyMember, Node template)
{
Common = ThingDomain.Present(common, "Common");
Collection = ThingDomain.Present(collection, "Collection");
KeyMember = ThingDomain.Present(keyMember, "KeyMember");
Template = ThingDomain.Present(template, "Template");
}
}
[MessagePackObject]
public sealed class OverlayNode : Node
{
[Key(0)] public NodeCommon Common { get; }
[Key(1)] public Anchor Anchor { get; }
[Key(2)] public bool Modal { get; }
[Key(3)] public CommandRef Dismiss { get; }
[Key(4)] public ImmutableArray<Node> Children { get; }
public OverlayNode(NodeCommon common, Anchor anchor, bool modal, CommandRef dismiss, IReadOnlyList<Node> children)
{
Common = ThingDomain.Present(common, "Common");
Anchor = ThingDomain.Present(anchor, "Anchor");
Modal = modal;
Dismiss = ThingDomain.Present(dismiss, "Dismiss");
Children = ThingDomain.Items(children, "Children");
}
}
[MessagePackObject]
public sealed class PlotNode : Node
{
[Key(0)] public NodeCommon Common { get; }
[Key(1)] public Bind Series { get; }
[Key(2)] public PlotMark Mark { get; }
[Key(3)] public double? XMin { get; }
[Key(4)] public double? XMax { get; }
[Key(5)] public double? YMin { get; }
[Key(6)] public double? YMax { get; }
public PlotNode(NodeCommon common, Bind series, PlotMark mark, double? xMin, double? xMax, double? yMin, double? yMax)
{
Common = ThingDomain.Present(common, "Common");
Series = ThingDomain.Present(series, "Series");
Mark = ThingDomain.Present(mark, "Mark");
XMin = xMin;
XMax = xMax;
YMin = yMin;
YMax = yMax;
}
}
[MessagePackObject]
public sealed class EmbedNode : Node
{
[Key(0)] public NodeCommon Common { get; }
[Key(1)] public string SlotKind { get; }
[Key(2)] public string SlotId { get; }
[Key(3)] public double Width { get; }
[Key(4)] public double Height { get; }
public EmbedNode(NodeCommon common, string slotKind, string slotId, double width, double height)
{
Common = ThingDomain.Present(common, "Common");
SlotKind = ThingDomain.Present(slotKind, "SlotKind");
SlotId = ThingDomain.Present(slotId, "SlotId");
Width = width;
Height = height;
}
}
[MessagePackObject]
public sealed class UseNode : Node
{
[Key(0)] public NodeCommon Common { get; }
[Key(1)] public CompositionRef Composition { get; }
[Key(2)] public ImmutableArray<Arg> Args { get; }
public UseNode(NodeCommon common, CompositionRef composition, IReadOnlyList<Arg> args)
{
Common = ThingDomain.Present(common, "Common");
Composition = ThingDomain.Present(composition, "Composition");
Args = ThingDomain.Items(args, "Args");
}
}
/// <summary>
/// Where a composition body places the nodes passed for its Slot parameter <c>Param</c>. Only a child
/// list of a composition body holds one, and resolve refuses it elsewhere. It carries no
/// <see cref="NodeCommon"/>: the argument's nodes, keeping their caller-scope ids, replace it.
/// </summary>
[MessagePackObject]
public sealed class SlotNode : Node
{
[Key(0)] public ParamName Param { get; }
public SlotNode(ParamName param)
{
Param = ThingDomain.Present(param, "Param");
}
}
[Union(0, typeof(ImageFitContain))]
[Union(1, typeof(ImageFitCover))]
[Union(2, typeof(ImageFitFill))]
[Union(3, typeof(ImageFitUnscaled))]
public abstract class ImageFit
{
internal ImageFit() { }
}
[MessagePackObject]
public sealed class ImageFitContain : ImageFit
{
public ImageFitContain() { }
}
[MessagePackObject]
public sealed class ImageFitCover : ImageFit
{
public ImageFitCover() { }
}
[MessagePackObject]
public sealed class ImageFitFill : ImageFit
{
public ImageFitFill() { }
}
[MessagePackObject]
public sealed class ImageFitUnscaled : ImageFit
{
public ImageFitUnscaled() { }
}
[Union(0, typeof(InputKindText))]
[Union(1, typeof(InputKindNumber))]
public abstract class InputKind
{
internal InputKind() { }
}
[MessagePackObject]
public sealed class InputKindText : InputKind
{
public InputKindText() { }
}
[MessagePackObject]
public sealed class InputKindNumber : InputKind
{
public InputKindNumber() { }
}
[Union(0, typeof(LiteralOptions))]
[Union(1, typeof(BoundOptions))]
public abstract class OptionList
{
internal OptionList() { }
}
[MessagePackObject]
public sealed class LiteralOptions : OptionList
{
[Key(0)] public ImmutableArray<SelectOption> Options { get; }
public LiteralOptions(IReadOnlyList<SelectOption> options)
{
Options = ThingDomain.Items(options, "Options");
}
}
[MessagePackObject]
public sealed class BoundOptions : OptionList
{
[Key(0)] public CollectionSource Collection { get; }
[Key(1)] public MemberPath ValueMember { get; }
[Key(2)] public MemberPath LabelMember { get; }
public BoundOptions(CollectionSource collection, MemberPath valueMember, MemberPath labelMember)
{
Collection = ThingDomain.Present(collection, "Collection");
ValueMember = ThingDomain.Present(valueMember, "ValueMember");
LabelMember = ThingDomain.Present(labelMember, "LabelMember");
}
}
[Union(0, typeof(AnchorViewport))]
[Union(1, typeof(AnchorNode))]
public abstract class Anchor
{
internal Anchor() { }
}
[MessagePackObject]
public sealed class AnchorViewport : Anchor
{
public AnchorViewport() { }
}
[MessagePackObject]
public sealed class AnchorNode : Anchor
{
[Key(0)] public string Node { get; }
public AnchorNode(string node)
{
Node = ThingDomain.Present(node, "Node");
}
}
[Union(0, typeof(PlotMarkLine))]
[Union(1, typeof(PlotMarkBar))]
[Union(2, typeof(PlotMarkArea))]
public abstract class PlotMark
{
internal PlotMark() { }
}
[MessagePackObject]
public sealed class PlotMarkLine : PlotMark
{
public PlotMarkLine() { }
}
[MessagePackObject]
public sealed class PlotMarkBar : PlotMark
{
public PlotMarkBar() { }
}
[MessagePackObject]
public sealed class PlotMarkArea : PlotMark
{
public PlotMarkArea() { }
}
[Union(0, typeof(TextArg))]
[Union(1, typeof(NumberArg))]
[Union(2, typeof(BoolArg))]
[Union(3, typeof(ArgValueBind))]
[Union(4, typeof(CollectionArg))]
[Union(5, typeof(CommandArg))]
[Union(6, typeof(SlotArg))]
public abstract class ArgValue
{
internal ArgValue() { }
}
[MessagePackObject]
public sealed class TextArg : ArgValue
{
[Key(0)] public string Value { get; }
public TextArg(string value)
{
Value = ThingDomain.Present(value, "Value");
}
}
[MessagePackObject]
public sealed class NumberArg : ArgValue
{
[Key(0)] public double Value { get; }
public NumberArg(double value)
{
Value = value;
}
}
[MessagePackObject]
public sealed class BoolArg : ArgValue
{
[Key(0)] public bool Value { get; }
public BoolArg(bool value)
{
Value = value;
}
}
[MessagePackObject]
public sealed class ArgValueBind : ArgValue
{
[Key(0)] public StateSource Source { get; }
[Key(1)] public MemberPath Member { get; }
[Key(2)] public Format? Format { get; }
public ArgValueBind(StateSource source, MemberPath member, Format? format)
{
Source = ThingDomain.Present(source, "Source");
Member = ThingDomain.Present(member, "Member");
Format = format;
}
}
[MessagePackObject]
public sealed class CollectionArg : ArgValue
{
[Key(0)] public CollectionSource Source { get; }
public CollectionArg(CollectionSource source)
{
Source = ThingDomain.Present(source, "Source");
}
}
[MessagePackObject]
public sealed class CommandArg : ArgValue
{
[Key(0)] public CommandRef Command { get; }
public CommandArg(CommandRef command)
{
Command = ThingDomain.Present(command, "Command");
}
}
[MessagePackObject]
public sealed class SlotArg : ArgValue
{
[Key(0)] public ImmutableArray<Node> Nodes { get; }
public SlotArg(IReadOnlyList<Node> nodes)
{
Nodes = ThingDomain.Items(nodes, "Nodes");
}
}
[Union(0, typeof(ParamKindText))]
[Union(1, typeof(ParamKindNumber))]
[Union(2, typeof(ParamKindBool))]
[Union(3, typeof(ParamKindBind))]
[Union(4, typeof(ParamKindCollection))]
[Union(5, typeof(ParamKindCommand))]
[Union(6, typeof(ParamKindSlot))]
public abstract class ParamKind
{
internal ParamKind() { }
}
[MessagePackObject]
public sealed class ParamKindText : ParamKind
{
public ParamKindText() { }
}
[MessagePackObject]
public sealed class ParamKindNumber : ParamKind
{
public ParamKindNumber() { }
}
[MessagePackObject]
public sealed class ParamKindBool : ParamKind
{
public ParamKindBool() { }
}
[MessagePackObject]
public sealed class ParamKindBind : ParamKind
{
public ParamKindBind() { }
}
[MessagePackObject]
public sealed class ParamKindCollection : ParamKind
{
public ParamKindCollection() { }
}
[MessagePackObject]
public sealed class ParamKindCommand : ParamKind
{
public ParamKindCommand() { }
}
[MessagePackObject]
public sealed class ParamKindSlot : ParamKind
{
public ParamKindSlot() { }
}
[MessagePackObject]
public sealed class NodeCommon
{
[Key(0)] public string Id { get; }
[Key(1)] public BoolSource Visible { get; }
[Key(2)] public TextSource? A11yLabel { get; }
public NodeCommon(string id, BoolSource visible, TextSource? a11yLabel)
{
Id = ThingDomain.Present(id, "Id");
Visible = ThingDomain.Present(visible, "Visible");
A11yLabel = a11yLabel;
}
}
[MessagePackObject]
public sealed class SelectOption
{
[Key(0)] public string Value { get; }
[Key(1)] public string Label { get; }
public SelectOption(string value, string label)
{
Value = ThingDomain.Present(value, "Value");
Label = ThingDomain.Present(label, "Label");
}
}
[MessagePackObject]
public sealed class CompositionRef
{
[Key(0)] public string Publisher { get; }
[Key(1)] public string Name { get; }
[Key(2)] public long Version { get; }
public CompositionRef(string publisher, string name, long version)
{
Publisher = ThingDomain.Present(publisher, "Publisher");
Name = ThingDomain.Segment(name);
Version = ThingDomain.Version(version);
}
}
[MessagePackObject]
public sealed class Arg
{
[Key(0)] public string Name { get; }
[Key(1)] public ArgValue Value { get; }
public Arg(string name, ArgValue value)
{
Name = ThingDomain.Present(name, "Name");
Value = ThingDomain.Present(value, "Value");
}
}
[MessagePackObject]
public sealed class ParamDecl
{
[Key(0)] public string Name { get; }
[Key(1)] public ParamKind Kind { get; }
public ParamDecl(string name, ParamKind kind)
{
Name = ThingDomain.Present(name, "Name");
Kind = ThingDomain.Present(kind, "Kind");
}
}
[CultDocument("gamecult.thing.surface", "gamecult.thing.surface.v1")]
[MessagePackObject]
public sealed class SurfaceDocument
{
[Key(0)] public string ProviderId { get; }
[Key(1)] public string Label { get; }
[Key(2)] public long Version { get; }
[Key(3)] public string Title { get; }
[Key(4)] public Node Root { get; }
[Key(5)] public ImmutableArray<CommandDecl> Commands { get; }
public SurfaceDocument(string providerId, string label, long version, string title, Node root, IReadOnlyList<CommandDecl> commands)
{
ProviderId = ThingDomain.Present(providerId, "ProviderId");
Label = ThingDomain.Segment(label);
Version = ThingDomain.Version(version);
Title = ThingDomain.Present(title, "Title");
Root = ThingDomain.Present(root, "Root");
Commands = ThingDomain.Items(commands, "Commands");
}
[IgnoreMember] public string RecordKey => ThingKeys.SurfaceKey(ProviderId, Label);
}
[CultDocument("gamecult.thing.composition", "gamecult.thing.composition.v1")]
[MessagePackObject]
public sealed class CompositionDocument
{
[Key(0)] public string Publisher { get; }
[Key(1)] public string Name { get; }
[Key(2)] public long Version { get; }
[Key(3)] public ImmutableArray<ParamDecl> Params { get; }
[Key(4)] public Node Body { get; }
public CompositionDocument(string publisher, string name, long version, IReadOnlyList<ParamDecl> @params, Node body)
{
Publisher = ThingDomain.Present(publisher, "Publisher");
Name = ThingDomain.Segment(name);
Version = ThingDomain.Version(version);
Params = ThingDomain.Items(@params, "Params");
Body = ThingDomain.Present(body, "Body");
}
[IgnoreMember] public string RecordKey => ThingKeys.CompositionKey(Publisher, Name, Version);
}

View file

@ -0,0 +1,132 @@
using System.Collections.Generic;
using GameCult.Caching;
using MessagePack;
namespace GameCult.Thing.Contract;
[Union(0, typeof(PendingOutcome))]
[Union(1, typeof(CompletedOutcome))]
[Union(2, typeof(DeniedOutcome))]
[Union(3, typeof(FailedOutcome))]
public abstract class Outcome
{
internal Outcome() { }
}
[MessagePackObject]
public sealed class PendingOutcome : Outcome
{
[Key(0)] public string Message { get; }
public PendingOutcome(string message)
{
Message = ThingDomain.Present(message, "Message");
}
}
[MessagePackObject]
public sealed class CompletedOutcome : Outcome
{
[Key(0)] public long? SourceVersion { get; }
[Key(1)] public bool ClearDrafts { get; }
[Key(2)] public Effect? Effect { get; }
public CompletedOutcome(long? sourceVersion, bool clearDrafts, Effect? effect)
{
SourceVersion = ThingDomain.Version(sourceVersion);
ClearDrafts = clearDrafts;
Effect = effect;
}
}
[MessagePackObject]
public sealed class DeniedOutcome : Outcome
{
[Key(0)] public string Reason { get; }
[Key(1)] public string? Node { get; }
public DeniedOutcome(string reason, string? node)
{
Reason = ThingDomain.Present(reason, "Reason");
Node = node;
}
}
[MessagePackObject]
public sealed class FailedOutcome : Outcome
{
[Key(0)] public string Reason { get; }
public FailedOutcome(string reason)
{
Reason = ThingDomain.Present(reason, "Reason");
}
}
[Union(0, typeof(OpenSurfaceEffect))]
[Union(1, typeof(OpenExternalEffect))]
public abstract class Effect
{
internal Effect() { }
}
[MessagePackObject]
public sealed class OpenSurfaceEffect : Effect
{
[Key(0)] public string Key { get; }
public OpenSurfaceEffect(string key)
{
Key = ThingDomain.Present(key, "Key");
}
}
[MessagePackObject]
public sealed class OpenExternalEffect : Effect
{
[Key(0)] public string Url { get; }
[Key(1)] public CommandRef Resume { get; }
public OpenExternalEffect(string url, CommandRef resume)
{
Url = ThingDomain.Present(url, "Url");
Resume = ThingDomain.Present(resume, "Resume");
}
}
/// <summary>
/// A provider's answer to one invocation. Results are built by the four factories and nothing else: the constructor is
/// private (MessagePack calls it on decode, and it holds the same <see cref="ThingDomain.Seq"/> bound), and no API takes a
/// state as free text or as an untyped value. <c>Seq</c> counts from 1 per invocation. The copied invocation id is a
/// convenience: core binds a result to an invocation it issued, so the copy is not provenance.
/// </summary>
[CultDocument("gamecult.thing.command_result", "gamecult.thing.command_result.v1")]
[MessagePackObject(AllowPrivate = true)]
public sealed class CommandResult
{
[Key(0)] public string InvocationId { get; }
[Key(1)] public int Seq { get; }
[Key(2)] public Outcome Outcome { get; }
[SerializationConstructor]
private CommandResult(string invocationId, int seq, Outcome outcome)
{
InvocationId = ThingDomain.Present(invocationId, "InvocationId");
Seq = ThingDomain.Seq(seq);
Outcome = ThingDomain.Present(outcome, "Outcome");
}
[IgnoreMember] public string RecordKey => ThingKeys.ResultKey(InvocationId, Seq);
public static CommandResult Pending(CommandInvocation invocation, int seq, string message) =>
new(ThingDomain.Present(invocation, "Invocation").InvocationId, seq, new PendingOutcome(message));
public static CommandResult Completed(CommandInvocation invocation, int seq, long? sourceVersion, bool clearDrafts, Effect? effect) =>
new(ThingDomain.Present(invocation, "Invocation").InvocationId, seq, new CompletedOutcome(sourceVersion, clearDrafts, effect));
public static CommandResult Denied(CommandInvocation invocation, int seq, string reason, string? node) =>
new(ThingDomain.Present(invocation, "Invocation").InvocationId, seq, new DeniedOutcome(reason, node));
public static CommandResult Failed(CommandInvocation invocation, int seq, string reason) =>
new(ThingDomain.Present(invocation, "Invocation").InvocationId, seq, new FailedOutcome(reason));
}

View file

@ -0,0 +1,337 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using GameCult.Caching;
using MessagePack;
namespace GameCult.Thing.Contract;
/// <summary>
/// A parameter named, where Rust's ParamName is a field (<see cref="SlotNode.Param"/>). Where it is an
/// arm payload, the arm class (TextSourceParam and the rest) carries Name itself.
/// </summary>
[MessagePackObject]
public sealed class ParamName
{
[Key(0)] public string Name { get; }
public ParamName(string name)
{
Name = ThingDomain.Present(name, "Name");
}
}
[Union(0, typeof(TextLiteral))]
[Union(1, typeof(TextSourceBound))]
[Union(2, typeof(TextSourceParam))]
public abstract class TextSource
{
internal TextSource() { }
}
[MessagePackObject]
public sealed class TextLiteral : TextSource
{
[Key(0)] public string Value { get; }
public TextLiteral(string value)
{
Value = ThingDomain.Present(value, "Value");
}
}
[MessagePackObject]
public sealed class TextSourceBound : TextSource
{
[Key(0)] public StateSource Source { get; }
[Key(1)] public MemberPath Member { get; }
[Key(2)] public Format? Format { get; }
public TextSourceBound(StateSource source, MemberPath member, Format? format)
{
Source = ThingDomain.Present(source, "Source");
Member = ThingDomain.Present(member, "Member");
Format = format;
}
}
[MessagePackObject]
public sealed class TextSourceParam : TextSource
{
[Key(0)] public string Name { get; }
public TextSourceParam(string name)
{
Name = ThingDomain.Present(name, "Name");
}
}
[Union(0, typeof(NumberLiteral))]
[Union(1, typeof(NumberSourceBound))]
[Union(2, typeof(NumberSourceParam))]
public abstract class NumberSource
{
internal NumberSource() { }
}
[MessagePackObject]
public sealed class NumberLiteral : NumberSource
{
[Key(0)] public double Value { get; }
public NumberLiteral(double value)
{
Value = value;
}
}
[MessagePackObject]
public sealed class NumberSourceBound : NumberSource
{
[Key(0)] public StateSource Source { get; }
[Key(1)] public MemberPath Member { get; }
[Key(2)] public Format? Format { get; }
public NumberSourceBound(StateSource source, MemberPath member, Format? format)
{
Source = ThingDomain.Present(source, "Source");
Member = ThingDomain.Present(member, "Member");
Format = format;
}
}
[MessagePackObject]
public sealed class NumberSourceParam : NumberSource
{
[Key(0)] public string Name { get; }
public NumberSourceParam(string name)
{
Name = ThingDomain.Present(name, "Name");
}
}
[Union(0, typeof(BoolLiteral))]
[Union(1, typeof(BoolSourceBound))]
[Union(2, typeof(BoolSourceParam))]
public abstract class BoolSource
{
internal BoolSource() { }
}
[MessagePackObject]
public sealed class BoolLiteral : BoolSource
{
[Key(0)] public bool Value { get; }
public BoolLiteral(bool value)
{
Value = value;
}
}
[MessagePackObject]
public sealed class BoolSourceBound : BoolSource
{
[Key(0)] public StateSource Source { get; }
[Key(1)] public MemberPath Member { get; }
[Key(2)] public Format? Format { get; }
public BoolSourceBound(StateSource source, MemberPath member, Format? format)
{
Source = ThingDomain.Present(source, "Source");
Member = ThingDomain.Present(member, "Member");
Format = format;
}
}
[MessagePackObject]
public sealed class BoolSourceParam : BoolSource
{
[Key(0)] public string Name { get; }
public BoolSourceParam(string name)
{
Name = ThingDomain.Present(name, "Name");
}
}
[Union(0, typeof(StateRef))]
[Union(1, typeof(StateSourceItem))]
public abstract class StateSource
{
internal StateSource() { }
}
[MessagePackObject]
public sealed class StateRef : StateSource
{
[Key(0)] public string? Provider { get; }
[Key(1)] public string Schema { get; }
[Key(2)] public string Key { get; }
public StateRef(string? provider, string schema, string key)
{
Provider = provider;
Schema = ThingDomain.Present(schema, "Schema");
Key = ThingDomain.Present(key, "Key");
}
}
[MessagePackObject]
public sealed class StateSourceItem : StateSource
{
public StateSourceItem() { }
}
[Union(0, typeof(MemberName))]
[Union(1, typeof(MemberIndex))]
public abstract class MemberStep
{
internal MemberStep() { }
}
[MessagePackObject]
public sealed class MemberName : MemberStep
{
[Key(0)] public string Name { get; }
public MemberName(string name)
{
Name = ThingDomain.Present(name, "Name");
}
}
[MessagePackObject]
public sealed class MemberIndex : MemberStep
{
[Key(0)] public int Index { get; }
public MemberIndex(int index)
{
Index = ThingDomain.Count(index);
}
}
[Union(0, typeof(NumberFormat))]
[Union(1, typeof(FormatDuration))]
[Union(2, typeof(FormatTimestamp))]
[Union(3, typeof(AffixFormat))]
public abstract class Format
{
internal Format() { }
}
[MessagePackObject]
public sealed class NumberFormat : Format
{
[Key(0)] public int Precision { get; }
[Key(1)] public bool Percent { get; }
[Key(2)] public string? Unit { get; }
public NumberFormat(int precision, bool percent, string? unit)
{
Precision = ThingDomain.Count(precision);
Percent = percent;
Unit = unit;
}
}
[MessagePackObject]
public sealed class FormatDuration : Format
{
public FormatDuration() { }
}
[MessagePackObject]
public sealed class FormatTimestamp : Format
{
public FormatTimestamp() { }
}
[MessagePackObject]
public sealed class AffixFormat : Format
{
[Key(0)] public string Prefix { get; }
[Key(1)] public string Suffix { get; }
public AffixFormat(string prefix, string suffix)
{
Prefix = ThingDomain.Present(prefix, "Prefix");
Suffix = ThingDomain.Present(suffix, "Suffix");
}
}
[Union(0, typeof(RecordsSource))]
[Union(1, typeof(CollectionSourceMember))]
[Union(2, typeof(CollectionSourceParam))]
public abstract class CollectionSource
{
internal CollectionSource() { }
}
[MessagePackObject]
public sealed class RecordsSource : CollectionSource
{
[Key(0)] public string? Provider { get; }
[Key(1)] public string Schema { get; }
[Key(2)] public string KeyPrefix { get; }
public RecordsSource(string? provider, string schema, string keyPrefix)
{
Provider = provider;
Schema = ThingDomain.Present(schema, "Schema");
KeyPrefix = ThingDomain.Present(keyPrefix, "KeyPrefix");
}
}
[MessagePackObject]
public sealed class CollectionSourceMember : CollectionSource
{
[Key(0)] public StateSource Source { get; }
[Key(1)] public MemberPath Member { get; }
[Key(2)] public Format? Format { get; }
public CollectionSourceMember(StateSource source, MemberPath member, Format? format)
{
Source = ThingDomain.Present(source, "Source");
Member = ThingDomain.Present(member, "Member");
Format = format;
}
}
[MessagePackObject]
public sealed class CollectionSourceParam : CollectionSource
{
[Key(0)] public string Name { get; }
public CollectionSourceParam(string name)
{
Name = ThingDomain.Present(name, "Name");
}
}
[MessagePackObject]
public sealed class Bind
{
[Key(0)] public StateSource Source { get; }
[Key(1)] public MemberPath Member { get; }
[Key(2)] public Format? Format { get; }
public Bind(StateSource source, MemberPath member, Format? format)
{
Source = ThingDomain.Present(source, "Source");
Member = ThingDomain.Present(member, "Member");
Format = format;
}
}
[MessagePackObject]
public sealed class MemberPath
{
[Key(0)] public ImmutableArray<MemberStep> Steps { get; }
public MemberPath(IReadOnlyList<MemberStep> steps)
{
Steps = ThingDomain.Items(steps, "Steps");
}
}

View file

@ -0,0 +1,497 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using GameCult.Caching;
using MessagePack;
namespace GameCult.Thing.Contract;
[Union(0, typeof(DimensionPx))]
[Union(1, typeof(DimensionPercent))]
[Union(2, typeof(DimensionFr))]
[Union(3, typeof(DimensionAuto))]
[Union(4, typeof(DimensionContent))]
public abstract class Dimension
{
internal Dimension() { }
}
[MessagePackObject]
public sealed class DimensionPx : Dimension
{
[Key(0)] public double Value { get; }
public DimensionPx(double value)
{
Value = value;
}
}
[MessagePackObject]
public sealed class DimensionPercent : Dimension
{
[Key(0)] public double Value { get; }
public DimensionPercent(double value)
{
Value = value;
}
}
[MessagePackObject]
public sealed class DimensionFr : Dimension
{
[Key(0)] public double Value { get; }
public DimensionFr(double value)
{
Value = value;
}
}
[MessagePackObject]
public sealed class DimensionAuto : Dimension
{
public DimensionAuto() { }
}
[MessagePackObject]
public sealed class DimensionContent : Dimension
{
public DimensionContent() { }
}
[Union(0, typeof(DisplayFlex))]
[Union(1, typeof(DisplayGrid))]
[Union(2, typeof(DisplayBlock))]
public abstract class Display
{
internal Display() { }
}
[MessagePackObject]
public sealed class DisplayFlex : Display
{
public DisplayFlex() { }
}
[MessagePackObject]
public sealed class DisplayGrid : Display
{
public DisplayGrid() { }
}
[MessagePackObject]
public sealed class DisplayBlock : Display
{
public DisplayBlock() { }
}
[Union(0, typeof(DirectionRow))]
[Union(1, typeof(DirectionColumn))]
[Union(2, typeof(DirectionRowReverse))]
[Union(3, typeof(DirectionColumnReverse))]
public abstract class Direction
{
internal Direction() { }
}
[MessagePackObject]
public sealed class DirectionRow : Direction
{
public DirectionRow() { }
}
[MessagePackObject]
public sealed class DirectionColumn : Direction
{
public DirectionColumn() { }
}
[MessagePackObject]
public sealed class DirectionRowReverse : Direction
{
public DirectionRowReverse() { }
}
[MessagePackObject]
public sealed class DirectionColumnReverse : Direction
{
public DirectionColumnReverse() { }
}
[Union(0, typeof(WrapNoWrap))]
[Union(1, typeof(WrapWrap))]
[Union(2, typeof(WrapWrapReverse))]
public abstract class Wrap
{
internal Wrap() { }
}
[MessagePackObject]
public sealed class WrapNoWrap : Wrap
{
public WrapNoWrap() { }
}
[MessagePackObject]
public sealed class WrapWrap : Wrap
{
public WrapWrap() { }
}
[MessagePackObject]
public sealed class WrapWrapReverse : Wrap
{
public WrapWrapReverse() { }
}
[Union(0, typeof(PositionRelative))]
[Union(1, typeof(PositionAbsolute))]
public abstract class Position
{
internal Position() { }
}
[MessagePackObject]
public sealed class PositionRelative : Position
{
public PositionRelative() { }
}
[MessagePackObject]
public sealed class PositionAbsolute : Position
{
public PositionAbsolute() { }
}
[Union(0, typeof(OverflowVisible))]
[Union(1, typeof(OverflowClip))]
[Union(2, typeof(OverflowScroll))]
public abstract class Overflow
{
internal Overflow() { }
}
[MessagePackObject]
public sealed class OverflowVisible : Overflow
{
public OverflowVisible() { }
}
[MessagePackObject]
public sealed class OverflowClip : Overflow
{
public OverflowClip() { }
}
[MessagePackObject]
public sealed class OverflowScroll : Overflow
{
public OverflowScroll() { }
}
[Union(0, typeof(ItemAlignAuto))]
[Union(1, typeof(ItemAlignStart))]
[Union(2, typeof(ItemAlignEnd))]
[Union(3, typeof(ItemAlignCenter))]
[Union(4, typeof(ItemAlignStretch))]
[Union(5, typeof(ItemAlignBaseline))]
public abstract class ItemAlign
{
internal ItemAlign() { }
}
[MessagePackObject]
public sealed class ItemAlignAuto : ItemAlign
{
public ItemAlignAuto() { }
}
[MessagePackObject]
public sealed class ItemAlignStart : ItemAlign
{
public ItemAlignStart() { }
}
[MessagePackObject]
public sealed class ItemAlignEnd : ItemAlign
{
public ItemAlignEnd() { }
}
[MessagePackObject]
public sealed class ItemAlignCenter : ItemAlign
{
public ItemAlignCenter() { }
}
[MessagePackObject]
public sealed class ItemAlignStretch : ItemAlign
{
public ItemAlignStretch() { }
}
[MessagePackObject]
public sealed class ItemAlignBaseline : ItemAlign
{
public ItemAlignBaseline() { }
}
[Union(0, typeof(ContentAlignAuto))]
[Union(1, typeof(ContentAlignStart))]
[Union(2, typeof(ContentAlignEnd))]
[Union(3, typeof(ContentAlignCenter))]
[Union(4, typeof(ContentAlignStretch))]
[Union(5, typeof(ContentAlignSpaceBetween))]
[Union(6, typeof(ContentAlignSpaceAround))]
[Union(7, typeof(ContentAlignSpaceEvenly))]
public abstract class ContentAlign
{
internal ContentAlign() { }
}
[MessagePackObject]
public sealed class ContentAlignAuto : ContentAlign
{
public ContentAlignAuto() { }
}
[MessagePackObject]
public sealed class ContentAlignStart : ContentAlign
{
public ContentAlignStart() { }
}
[MessagePackObject]
public sealed class ContentAlignEnd : ContentAlign
{
public ContentAlignEnd() { }
}
[MessagePackObject]
public sealed class ContentAlignCenter : ContentAlign
{
public ContentAlignCenter() { }
}
[MessagePackObject]
public sealed class ContentAlignStretch : ContentAlign
{
public ContentAlignStretch() { }
}
[MessagePackObject]
public sealed class ContentAlignSpaceBetween : ContentAlign
{
public ContentAlignSpaceBetween() { }
}
[MessagePackObject]
public sealed class ContentAlignSpaceAround : ContentAlign
{
public ContentAlignSpaceAround() { }
}
[MessagePackObject]
public sealed class ContentAlignSpaceEvenly : ContentAlign
{
public ContentAlignSpaceEvenly() { }
}
[Union(0, typeof(ThemeToken))]
[Union(1, typeof(Rgba))]
public abstract class ColorRef
{
internal ColorRef() { }
}
[MessagePackObject]
public sealed class ThemeToken : ColorRef
{
[Key(0)] public string Name { get; }
public ThemeToken(string name)
{
Name = ThingDomain.Present(name, "Name");
}
}
[MessagePackObject]
public sealed class Rgba : ColorRef
{
[Key(0)] public byte R { get; }
[Key(1)] public byte G { get; }
[Key(2)] public byte B { get; }
[Key(3)] public byte A { get; }
public Rgba(byte r, byte g, byte b, byte a)
{
R = r;
G = g;
B = b;
A = a;
}
}
[Union(0, typeof(RoleGroup))]
[Union(1, typeof(RoleRegion))]
[Union(2, typeof(RoleList))]
[Union(3, typeof(RoleListItem))]
[Union(4, typeof(RoleHeading))]
[Union(5, typeof(RoleDialog))]
[Union(6, typeof(RoleToolbar))]
public abstract class Role
{
internal Role() { }
}
[MessagePackObject]
public sealed class RoleGroup : Role
{
public RoleGroup() { }
}
[MessagePackObject]
public sealed class RoleRegion : Role
{
public RoleRegion() { }
}
[MessagePackObject]
public sealed class RoleList : Role
{
public RoleList() { }
}
[MessagePackObject]
public sealed class RoleListItem : Role
{
public RoleListItem() { }
}
[MessagePackObject]
public sealed class RoleHeading : Role
{
public RoleHeading() { }
}
[MessagePackObject]
public sealed class RoleDialog : Role
{
public RoleDialog() { }
}
[MessagePackObject]
public sealed class RoleToolbar : Role
{
public RoleToolbar() { }
}
[MessagePackObject]
public sealed class Size2
{
[Key(0)] public Dimension Width { get; }
[Key(1)] public Dimension Height { get; }
public Size2(Dimension width, Dimension height)
{
Width = ThingDomain.Present(width, "Width");
Height = ThingDomain.Present(height, "Height");
}
}
[MessagePackObject]
public sealed class Edges
{
[Key(0)] public Dimension Top { get; }
[Key(1)] public Dimension Right { get; }
[Key(2)] public Dimension Bottom { get; }
[Key(3)] public Dimension Left { get; }
public Edges(Dimension top, Dimension right, Dimension bottom, Dimension left)
{
Top = ThingDomain.Present(top, "Top");
Right = ThingDomain.Present(right, "Right");
Bottom = ThingDomain.Present(bottom, "Bottom");
Left = ThingDomain.Present(left, "Left");
}
}
[MessagePackObject]
public sealed class BoxStyle
{
[Key(0)] public Display Display { get; }
[Key(1)] public Direction Direction { get; }
[Key(2)] public Wrap Wrap { get; }
[Key(3)] public Size2 Gap { get; }
[Key(4)] public Edges Padding { get; }
[Key(5)] public Edges Margin { get; }
[Key(6)] public Size2 Size { get; }
[Key(7)] public Size2 MinSize { get; }
[Key(8)] public Size2 MaxSize { get; }
[Key(9)] public Position Position { get; }
[Key(10)] public Edges Inset { get; }
[Key(11)] public Overflow Overflow { get; }
[Key(12)] public ItemAlign AlignItems { get; }
[Key(13)] public ItemAlign AlignSelf { get; }
[Key(14)] public ContentAlign AlignContent { get; }
[Key(15)] public ContentAlign JustifyContent { get; }
[Key(16)] public double Grow { get; }
[Key(17)] public double Shrink { get; }
[Key(18)] public Dimension Basis { get; }
[Key(19)] public ImmutableArray<Dimension> GridColumns { get; }
[Key(20)] public ImmutableArray<Dimension> GridRows { get; }
public BoxStyle(Display display, Direction direction, Wrap wrap, Size2 gap, Edges padding, Edges margin, Size2 size, Size2 minSize, Size2 maxSize, Position position, Edges inset, Overflow overflow, ItemAlign alignItems, ItemAlign alignSelf, ContentAlign alignContent, ContentAlign justifyContent, double grow, double shrink, Dimension basis, IReadOnlyList<Dimension> gridColumns, IReadOnlyList<Dimension> gridRows)
{
Display = ThingDomain.Present(display, "Display");
Direction = ThingDomain.Present(direction, "Direction");
Wrap = ThingDomain.Present(wrap, "Wrap");
Gap = ThingDomain.Present(gap, "Gap");
Padding = ThingDomain.Present(padding, "Padding");
Margin = ThingDomain.Present(margin, "Margin");
Size = ThingDomain.Present(size, "Size");
MinSize = ThingDomain.Present(minSize, "MinSize");
MaxSize = ThingDomain.Present(maxSize, "MaxSize");
Position = ThingDomain.Present(position, "Position");
Inset = ThingDomain.Present(inset, "Inset");
Overflow = ThingDomain.Present(overflow, "Overflow");
AlignItems = ThingDomain.Present(alignItems, "AlignItems");
AlignSelf = ThingDomain.Present(alignSelf, "AlignSelf");
AlignContent = ThingDomain.Present(alignContent, "AlignContent");
JustifyContent = ThingDomain.Present(justifyContent, "JustifyContent");
Grow = grow;
Shrink = shrink;
Basis = ThingDomain.Present(basis, "Basis");
GridColumns = ThingDomain.Items(gridColumns, "GridColumns");
GridRows = ThingDomain.Items(gridRows, "GridRows");
}
}
[MessagePackObject]
public sealed class Border
{
[Key(0)] public ColorRef Color { get; }
[Key(1)] public double Width { get; }
public Border(ColorRef color, double width)
{
Color = ThingDomain.Present(color, "Color");
Width = width;
}
}
[MessagePackObject]
public sealed class Paint
{
[Key(0)] public ColorRef? Background { get; }
[Key(1)] public Border? Border { get; }
[Key(2)] public double Radius { get; }
public Paint(ColorRef? background, Border? border, double radius)
{
Background = background;
Border = border;
Radius = radius;
}
}

View file

@ -0,0 +1,71 @@
{
"name": "@gamecult/thing-contract",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@gamecult/thing-contract",
"version": "0.1.0",
"license": "MIT",
"dependencies": {
"@gamecult/cultcache-ts": "file:../../../CultLib/packages/cultcache-ts"
},
"devDependencies": {
"@types/node": "^24.0.0",
"typescript": "^5.9.0"
}
},
"../../../CultLib/packages/cultcache-ts": {
"name": "@gamecult/cultcache-ts",
"version": "0.14.0",
"license": "MIT",
"dependencies": {
"@msgpack/msgpack": "^3.1.3",
"zod": "^3.25.76"
},
"devDependencies": {
"@types/node": "^24.0.0",
"typescript": "^5.9.0"
},
"engines": {
"node": ">=20"
}
},
"node_modules/@gamecult/cultcache-ts": {
"resolved": "../../../CultLib/packages/cultcache-ts",
"link": true
},
"node_modules/@types/node": {
"version": "24.19.2",
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.19.2.tgz",
"integrity": "sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": ">=7.24.0 <7.24.7"
}
},
"node_modules/typescript": {
"version": "5.9.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=14.17"
}
},
"node_modules/undici-types": {
"version": "7.24.6",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz",
"integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==",
"dev": true,
"license": "MIT"
}
}
}

View file

@ -0,0 +1,29 @@
{
"name": "@gamecult/thing-contract",
"version": "0.1.0",
"description": "The gamecult.thing.* wire types and codecs for TypeScript, held byte for byte to the Rust crate's goldens.",
"type": "module",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
}
},
"files": [
"dist"
],
"scripts": {
"build": "tsc -p tsconfig.json",
"test": "tsc -p tsconfig.json && tsc -p tsconfig.test.json && node --test dist-test/test/*.test.js"
},
"dependencies": {
"@gamecult/cultcache-ts": "file:../../../CultLib/packages/cultcache-ts"
},
"devDependencies": {
"@types/node": "^24.0.0",
"typescript": "^5.9.0"
},
"license": "MIT"
}

View file

@ -0,0 +1,536 @@
// One codec per type of crates/thing-contract, built from cultcache-ts's slots, union, nullable and lazy at the crate's
// slot and arm keys. Nothing here encodes or decodes by hand, declares a slot default, or checks an arm: the library's
// codecs refuse an unknown arm or a missing slot, domain.ts holds the five domains and the presence of a slot.
//
// Presence follows the Rust types: a slot is nullable exactly where the Rust member is an Option, and every other string,
// bytes, record, list and union slot refuses nil on decode and null or undefined on encode (`present`). The vector that
// proves it is crates/thing-contract/tests/goldens/nil-positions.tsv.
//
// Every slots and union codec is named GameCult.Thing.Contract.<C# name>, the reference's full type name, because a
// store's schema catalog carries the type name of each document slot and the reference compares them. The C# package
// owns the names (tests/thing-contract-parity/type-names.txt): where C# flattens a Rust type into its arms, there is one
// codec per arm.
//
// Definition order is dependency order. The one cycle is Node (through Box, Button, Overlay, Repeat and Slot), and it
// closes at slot level with `lazy`, never inside a union's arm table.
import { codecs } from "@gamecult/cultcache-ts";
import type { Codec } from "@gamecult/cultcache-ts";
import { channel, count, present, segment, text, version } from "./domain.js";
import type * as T from "./types.js";
const { string, boolean, float64, bytes, nullable, lazy, unit, list: sequence } = codecs;
const named = (name: string): string => `GameCult.Thing.Contract.${name}`;
const blob = present(bytes);
// The C# member type of a list slot is ImmutableArray<T>, a whole-value holder; cultcache-ts names only List<T>
// (a stopgap, until thing2:follow_up:cultcache-ts-readonly-list-name lands). A list slot is required.
const readOnlyList = <TItem>(item: Codec<TItem>): Codec<TItem[]> => {
const inner = sequence(item);
const readOnly: Codec<TItem[]> = {
get typeName() {
return item.typeName === undefined ? undefined : `System.Collections.Immutable.ImmutableArray<${item.typeName}>`;
},
encode: (value) => inner.encode(value),
decode: (raw) => inner.decode(raw),
};
return present(readOnly);
};
// source.rs
export const paramName = present(codecs.slots<T.ParamName>({ 0: ["name", text] }, named("ParamName")));
export const textSourceParam = present(codecs.slots<T.ParamName>({ 0: ["name", text] }, named("TextSourceParam")));
export const numberSourceParam = present(codecs.slots<T.ParamName>({ 0: ["name", text] }, named("NumberSourceParam")));
export const boolSourceParam = present(codecs.slots<T.ParamName>({ 0: ["name", text] }, named("BoolSourceParam")));
export const collectionSourceParam = present(codecs.slots<T.ParamName>({ 0: ["name", text] }, named("CollectionSourceParam")));
export const commandRefParam = present(codecs.slots<T.ParamName>({ 0: ["name", text] }, named("CommandRefParam")));
export const textLiteral = present(codecs.slots<T.TextLiteral>({ 0: ["value", text] }, named("TextLiteral")));
export const numberLiteral = present(codecs.slots<T.NumberLiteral>({ 0: ["value", float64] }, named("NumberLiteral")));
export const boolLiteral = present(codecs.slots<T.BoolLiteral>({ 0: ["value", boolean] }, named("BoolLiteral")));
export const memberName = present(codecs.slots<T.MemberName>({ 0: ["name", text] }, named("MemberName")));
export const memberIndex = present(codecs.slots<T.MemberIndex>({ 0: ["index", count] }, named("MemberIndex")));
export const memberStep = present(
codecs.union<T.MemberStep>("MemberStep", { 0: ["Name", memberName], 1: ["Index", memberIndex] }, named("MemberStep")),
);
export const memberPath = present(codecs.slots<T.MemberPath>({ 0: ["steps", readOnlyList(memberStep)] }, named("MemberPath")));
export const numberFormat = present(codecs.slots<T.NumberFormat>(
{ 0: ["precision", count], 1: ["percent", boolean], 2: ["unit", nullable(string)] },
named("NumberFormat"),
));
export const affixFormat = present(codecs.slots<T.AffixFormat>({ 0: ["prefix", text], 1: ["suffix", text] }, named("AffixFormat")));
const formatRaw = codecs.union<T.Format>(
"Format",
{ 0: ["Number", numberFormat], 1: ["Duration", unit], 2: ["Timestamp", unit], 3: ["Affix", affixFormat] },
named("Format"),
);
export const format = present(formatRaw);
export const stateRef = present(codecs.slots<T.StateRef>(
{ 0: ["provider", nullable(string)], 1: ["schema", text], 2: ["key", text] },
named("StateRef"),
));
export const stateSource = present(
codecs.union<T.StateSource>("StateSource", { 0: ["Record", stateRef], 1: ["Item", unit] }, named("StateSource")),
);
export const bind = present(codecs.slots<T.Bind>(
{ 0: ["source", stateSource], 1: ["member", memberPath], 2: ["format", nullable(formatRaw)] },
named("Bind"),
));
const textSourceRaw = codecs.union<T.TextSource>(
"TextSource",
{ 0: ["Literal", textLiteral], 1: ["Bound", bind], 2: ["Param", textSourceParam] },
named("TextSource"),
);
export const textSource = present(textSourceRaw);
export const numberSource = present(
codecs.union<T.NumberSource>(
"NumberSource",
{ 0: ["Literal", numberLiteral], 1: ["Bound", bind], 2: ["Param", numberSourceParam] },
named("NumberSource"),
),
);
export const boolSource = present(
codecs.union<T.BoolSource>(
"BoolSource",
{ 0: ["Literal", boolLiteral], 1: ["Bound", bind], 2: ["Param", boolSourceParam] },
named("BoolSource"),
),
);
export const recordsSource = present(codecs.slots<T.RecordsSource>(
{ 0: ["provider", nullable(string)], 1: ["schema", text], 2: ["keyPrefix", text] },
named("RecordsSource"),
));
export const collectionSource = present(
codecs.union<T.CollectionSource>(
"CollectionSource",
{ 0: ["Records", recordsSource], 1: ["Member", bind], 2: ["Param", collectionSourceParam] },
named("CollectionSource"),
),
);
// style.rs
export const dimensionPx = present(codecs.slots<T.Scalar>({ 0: ["value", float64] }, named("DimensionPx")));
export const dimensionPercent = present(codecs.slots<T.Scalar>({ 0: ["value", float64] }, named("DimensionPercent")));
export const dimensionFr = present(codecs.slots<T.Scalar>({ 0: ["value", float64] }, named("DimensionFr")));
export const dimension = present(
codecs.union<T.Dimension>(
"Dimension",
{ 0: ["Px", dimensionPx], 1: ["Percent", dimensionPercent], 2: ["Fr", dimensionFr], 3: ["Auto", unit], 4: ["Content", unit] },
named("Dimension"),
),
);
export const size2 = present(codecs.slots<T.Size2>({ 0: ["width", dimension], 1: ["height", dimension] }, named("Size2")));
export const edges = present(codecs.slots<T.Edges>(
{ 0: ["top", dimension], 1: ["right", dimension], 2: ["bottom", dimension], 3: ["left", dimension] },
named("Edges"),
));
export const display = present(
codecs.union<T.Display>("Display", { 0: ["Flex", unit], 1: ["Grid", unit], 2: ["Block", unit] }, named("Display")),
);
export const direction = present(
codecs.union<T.Direction>(
"Direction",
{ 0: ["Row", unit], 1: ["Column", unit], 2: ["RowReverse", unit], 3: ["ColumnReverse", unit] },
named("Direction"),
),
);
export const wrap = present(
codecs.union<T.Wrap>("Wrap", { 0: ["NoWrap", unit], 1: ["Wrap", unit], 2: ["WrapReverse", unit] }, named("Wrap")),
);
export const position = present(
codecs.union<T.Position>("Position", { 0: ["Relative", unit], 1: ["Absolute", unit] }, named("Position")),
);
export const overflow = present(
codecs.union<T.Overflow>("Overflow", { 0: ["Visible", unit], 1: ["Clip", unit], 2: ["Scroll", unit] }, named("Overflow")),
);
export const itemAlign = present(
codecs.union<T.ItemAlign>(
"ItemAlign",
{
0: ["Auto", unit],
1: ["Start", unit],
2: ["End", unit],
3: ["Center", unit],
4: ["Stretch", unit],
5: ["Baseline", unit],
},
named("ItemAlign"),
),
);
export const contentAlign = present(
codecs.union<T.ContentAlign>(
"ContentAlign",
{
0: ["Auto", unit],
1: ["Start", unit],
2: ["End", unit],
3: ["Center", unit],
4: ["Stretch", unit],
5: ["SpaceBetween", unit],
6: ["SpaceAround", unit],
7: ["SpaceEvenly", unit],
},
named("ContentAlign"),
),
);
export const boxStyle = present(codecs.slots<T.BoxStyle>(
{
0: ["display", display],
1: ["direction", direction],
2: ["wrap", wrap],
3: ["gap", size2],
4: ["padding", edges],
5: ["margin", edges],
6: ["size", size2],
7: ["minSize", size2],
8: ["maxSize", size2],
9: ["position", position],
10: ["inset", edges],
11: ["overflow", overflow],
12: ["alignItems", itemAlign],
13: ["alignSelf", itemAlign],
14: ["alignContent", contentAlign],
15: ["justifyContent", contentAlign],
16: ["grow", float64],
17: ["shrink", float64],
18: ["basis", dimension],
19: ["gridColumns", readOnlyList(dimension)],
20: ["gridRows", readOnlyList(dimension)],
},
named("BoxStyle"),
));
export const themeToken = present(codecs.slots<T.ThemeToken>({ 0: ["name", text] }, named("ThemeToken")));
export const rgba = present(codecs.slots<T.Rgba>(
{ 0: ["r", channel], 1: ["g", channel], 2: ["b", channel], 3: ["a", channel] },
named("Rgba"),
));
const colorRefRaw = codecs.union<T.ColorRef>("ColorRef", { 0: ["Token", themeToken], 1: ["Rgba", rgba] }, named("ColorRef"));
export const colorRef = present(colorRefRaw);
const borderRaw = codecs.slots<T.Border>({ 0: ["color", colorRef], 1: ["width", float64] }, named("Border"));
export const border = present(borderRaw);
export const paint = present(codecs.slots<T.Paint>(
{ 0: ["background", nullable(colorRefRaw)], 1: ["border", nullable(borderRaw)], 2: ["radius", float64] },
named("Paint"),
));
export const role = present(
codecs.union<T.Role>(
"Role",
{
0: ["Group", unit],
1: ["Region", unit],
2: ["List", unit],
3: ["ListItem", unit],
4: ["Heading", unit],
5: ["Dialog", unit],
6: ["Toolbar", unit],
},
named("Role"),
),
);
// command.rs
export const commandDecl = present(codecs.slots<T.CommandDecl>(
{ 0: ["id", text], 1: ["payloadSchema", text], 2: ["captures", readOnlyList(string)], 3: ["confirm", nullable(string)] },
named("CommandDecl"),
));
export const commandIdRef = present(codecs.slots<T.CommandIdRef>({ 0: ["id", text] }, named("CommandIdRef")));
export const commandRef = present(
codecs.union<T.CommandRef>("CommandRef", { 0: ["Id", commandIdRef], 1: ["Param", commandRefParam] }, named("CommandRef")),
);
export const recordPayload = present(codecs.slots<T.RecordPayload>(
{ 0: ["schema", text], 1: ["bytes", blob] },
named("RecordPayload"),
));
export const textValue = present(codecs.slots<T.TextValue>({ 0: ["value", text] }, named("TextValue")));
export const numberValue = present(codecs.slots<T.NumberValue>({ 0: ["value", float64] }, named("NumberValue")));
export const boolValue = present(codecs.slots<T.BoolValue>({ 0: ["value", boolean] }, named("BoolValue")));
export const choiceValue = present(codecs.slots<T.ChoiceValue>({ 0: ["value", text] }, named("ChoiceValue")));
export const inputValue = present(
codecs.union<T.InputValue>(
"InputValue",
{ 0: ["Text", textValue], 1: ["Number", numberValue], 2: ["Bool", boolValue], 3: ["Choice", choiceValue] },
named("InputValue"),
),
);
export const capturedInput = present(codecs.slots<T.CapturedInput>(
{ 0: ["node", text], 1: ["value", inputValue] },
named("CapturedInput"),
));
export const commandInvocation = codecs.slots<T.CommandInvocation>(
{
0: ["invocationId", text],
1: ["surfaceKey", text],
2: ["surfaceVersion", version],
3: ["command", text],
4: ["payload", recordPayload],
5: ["captured", readOnlyList(capturedInput)],
6: ["client", text],
7: ["issuedAt", text],
8: ["delegation", nullable(string)],
},
named("CommandInvocation"),
);
// result.rs
export const pendingOutcome = present(codecs.slots<T.PendingOutcome>({ 0: ["message", text] }, named("PendingOutcome")));
export const openSurfaceEffect = present(codecs.slots<T.OpenSurfaceEffect>({ 0: ["key", text] }, named("OpenSurfaceEffect")));
export const openExternalEffect = present(codecs.slots<T.OpenExternalEffect>(
{ 0: ["url", text], 1: ["resume", commandRef] },
named("OpenExternalEffect"),
));
const effectRaw = codecs.union<T.Effect>(
"Effect",
{ 0: ["OpenSurface", openSurfaceEffect], 1: ["OpenExternal", openExternalEffect] },
named("Effect"),
);
export const effect = present(effectRaw);
export const completedOutcome = present(codecs.slots<T.CompletedOutcome>(
{ 0: ["sourceVersion", nullable(version)], 1: ["clearDrafts", boolean], 2: ["effect", nullable(effectRaw)] },
named("CompletedOutcome"),
));
export const deniedOutcome = present(codecs.slots<T.DeniedOutcome>(
{ 0: ["reason", text], 1: ["node", nullable(string)] },
named("DeniedOutcome"),
));
export const failedOutcome = present(codecs.slots<T.FailedOutcome>({ 0: ["reason", text] }, named("FailedOutcome")));
export const outcome = present(
codecs.union<T.Outcome>(
"Outcome",
{ 0: ["Pending", pendingOutcome], 1: ["Completed", completedOutcome], 2: ["Denied", deniedOutcome], 3: ["Failed", failedOutcome] },
named("Outcome"),
),
);
// node.rs
export const nodeCommon = present(codecs.slots<T.NodeCommon>(
{ 0: ["id", text], 1: ["visible", boolSource], 2: ["a11yLabel", nullable(textSourceRaw)] },
named("NodeCommon"),
));
// Node closes its own cycle here and nowhere else.
export const node: Codec<T.Node> = lazy(() => nodeUnion);
export const boxNode = present(codecs.slots<T.BoxNode>(
{ 0: ["common", nodeCommon], 1: ["style", boxStyle], 2: ["paint", paint], 3: ["role", role], 4: ["children", readOnlyList(node)] },
named("BoxNode"),
));
export const textNode = present(codecs.slots<T.TextNode>(
{
0: ["common", nodeCommon],
1: ["content", textSource],
2: ["styleToken", text],
3: ["wrap", boolean],
4: ["maxLines", nullable(count)],
5: ["selectable", boolean],
},
named("TextNode"),
));
export const imageFit = present(
codecs.union<T.ImageFit>(
"ImageFit",
{ 0: ["Contain", unit], 1: ["Cover", unit], 2: ["Fill", unit], 3: ["Unscaled", unit] },
named("ImageFit"),
),
);
export const imageNode = present(codecs.slots<T.ImageNode>(
{ 0: ["common", nodeCommon], 1: ["catalog", text], 2: ["asset", text], 3: ["fit", imageFit], 4: ["alt", textSource] },
named("ImageNode"),
));
export const buttonNode = present(codecs.slots<T.ButtonNode>(
{ 0: ["common", nodeCommon], 1: ["content", readOnlyList(node)], 2: ["onActivate", commandRef], 3: ["enabled", boolSource] },
named("ButtonNode"),
));
export const toggleNode = present(codecs.slots<T.ToggleNode>(
{ 0: ["common", nodeCommon], 1: ["checked", boolSource], 2: ["onChange", commandRef] },
named("ToggleNode"),
));
export const sliderNode = present(codecs.slots<T.SliderNode>(
{
0: ["common", nodeCommon],
1: ["min", float64],
2: ["max", float64],
3: ["step", float64],
4: ["value", numberSource],
5: ["commit", commandRef],
},
named("SliderNode"),
));
export const inputKind = present(
codecs.union<T.InputKind>("InputKind", { 0: ["Text", unit], 1: ["Number", unit] }, named("InputKind")),
);
export const textInputNode = present(codecs.slots<T.TextInputNode>(
{
0: ["common", nodeCommon],
1: ["multiline", boolean],
2: ["inputKind", inputKind],
3: ["placeholder", textSource],
4: ["initial", textSource],
5: ["submit", commandRef],
},
named("TextInputNode"),
));
export const selectOption = present(codecs.slots<T.SelectOption>({ 0: ["value", text], 1: ["label", text] }, named("SelectOption")));
export const literalOptions = present(codecs.slots<T.LiteralOptions>({ 0: ["options", readOnlyList(selectOption)] }, named("LiteralOptions")));
export const boundOptions = present(codecs.slots<T.BoundOptions>(
{ 0: ["collection", collectionSource], 1: ["valueMember", memberPath], 2: ["labelMember", memberPath] },
named("BoundOptions"),
));
export const optionList = present(
codecs.union<T.OptionList>("OptionList", { 0: ["Literal", literalOptions], 1: ["Bound", boundOptions] }, named("OptionList")),
);
export const selectNode = present(codecs.slots<T.SelectNode>(
{ 0: ["common", nodeCommon], 1: ["options", optionList], 2: ["value", bind], 3: ["onChange", commandRef] },
named("SelectNode"),
));
export const repeatNode = present(codecs.slots<T.RepeatNode>(
{ 0: ["common", nodeCommon], 1: ["collection", collectionSource], 2: ["keyMember", memberPath], 3: ["template", node] },
named("RepeatNode"),
));
export const anchorNode = present(codecs.slots<T.AnchorNode>({ 0: ["node", text] }, named("AnchorNode")));
export const anchor = present(
codecs.union<T.Anchor>("Anchor", { 0: ["Viewport", unit], 1: ["Node", anchorNode] }, named("Anchor")),
);
export const overlayNode = present(codecs.slots<T.OverlayNode>(
{
0: ["common", nodeCommon],
1: ["anchor", anchor],
2: ["modal", boolean],
3: ["dismiss", commandRef],
4: ["children", readOnlyList(node)],
},
named("OverlayNode"),
));
export const plotMark = present(
codecs.union<T.PlotMark>("PlotMark", { 0: ["Line", unit], 1: ["Bar", unit], 2: ["Area", unit] }, named("PlotMark")),
);
export const plotNode = present(codecs.slots<T.PlotNode>(
{
0: ["common", nodeCommon],
1: ["series", bind],
2: ["mark", plotMark],
3: ["xMin", nullable(float64)],
4: ["xMax", nullable(float64)],
5: ["yMin", nullable(float64)],
6: ["yMax", nullable(float64)],
},
named("PlotNode"),
));
export const embedNode = present(codecs.slots<T.EmbedNode>(
{
0: ["common", nodeCommon],
1: ["slotKind", text],
2: ["slotId", text],
3: ["width", float64],
4: ["height", float64],
},
named("EmbedNode"),
));
export const compositionRef = present(codecs.slots<T.CompositionRef>(
{ 0: ["publisher", text], 1: ["name", segment], 2: ["version", version] },
named("CompositionRef"),
));
export const textArg = present(codecs.slots<T.TextArg>({ 0: ["value", text] }, named("TextArg")));
export const numberArg = present(codecs.slots<T.NumberArg>({ 0: ["value", float64] }, named("NumberArg")));
export const boolArg = present(codecs.slots<T.BoolArg>({ 0: ["value", boolean] }, named("BoolArg")));
export const collectionArg = present(codecs.slots<T.CollectionArg>({ 0: ["source", collectionSource] }, named("CollectionArg")));
export const commandArg = present(codecs.slots<T.CommandArg>({ 0: ["command", commandRef] }, named("CommandArg")));
export const slotArg = present(codecs.slots<T.SlotArg>({ 0: ["nodes", readOnlyList(node)] }, named("SlotArg")));
export const argValue = present(
codecs.union<T.ArgValue>(
"ArgValue",
{
0: ["Text", textArg],
1: ["Number", numberArg],
2: ["Bool", boolArg],
3: ["Bind", bind],
4: ["Collection", collectionArg],
5: ["Command", commandArg],
6: ["Slot", slotArg],
},
named("ArgValue"),
),
);
export const arg = present(codecs.slots<T.Arg>({ 0: ["name", text], 1: ["value", argValue] }, named("Arg")));
export const useNode = present(codecs.slots<T.UseNode>(
{ 0: ["common", nodeCommon], 1: ["composition", compositionRef], 2: ["args", readOnlyList(arg)] },
named("UseNode"),
));
export const slotNode = present(codecs.slots<T.SlotNode>({ 0: ["param", paramName] }, named("SlotNode")));
const nodeUnion = present(
codecs.union<T.Node>(
"Node",
{
0: ["Box", boxNode],
1: ["Text", textNode],
2: ["Image", imageNode],
3: ["Button", buttonNode],
4: ["Toggle", toggleNode],
5: ["Slider", sliderNode],
6: ["TextInput", textInputNode],
7: ["Select", selectNode],
8: ["Repeat", repeatNode],
9: ["Overlay", overlayNode],
10: ["Plot", plotNode],
11: ["Embed", embedNode],
12: ["Use", useNode],
13: ["Slot", slotNode],
},
named("Node"),
),
);
export const paramKind = present(
codecs.union<T.ParamKind>(
"ParamKind",
{
0: ["Text", unit],
1: ["Number", unit],
2: ["Bool", unit],
3: ["Bind", unit],
4: ["Collection", unit],
5: ["Command", unit],
6: ["Slot", unit],
},
named("ParamKind"),
),
);
export const paramDecl = present(codecs.slots<T.ParamDecl>({ 0: ["name", text], 1: ["kind", paramKind] }, named("ParamDecl")));
// The documents' slot records. CommandResult's is in result.ts: it is the one that mints an instance.
export const surfaceDocument = codecs.slots<T.SurfaceDocument>(
{
0: ["providerId", text],
1: ["label", segment],
2: ["version", version],
3: ["title", text],
4: ["root", node],
5: ["commands", readOnlyList(commandDecl)],
},
named("SurfaceDocument"),
);
export const compositionDocument = codecs.slots<T.CompositionDocument>(
{
0: ["publisher", text],
1: ["name", segment],
2: ["version", version],
3: ["params", readOnlyList(paramDecl)],
4: ["body", node],
},
named("CompositionDocument"),
);
export const assetEntry = present(codecs.slots<T.AssetEntry>(
{ 0: ["id", text], 1: ["mediaType", text], 2: ["uri", text], 3: ["width", count], 4: ["height", count] },
named("AssetEntry"),
));
export const assetCatalog = codecs.slots<T.AssetCatalog>(
{ 0: ["providerId", text], 1: ["catalogId", segment], 2: ["version", version], 3: ["assets", readOnlyList(assetEntry)] },
named("AssetCatalog"),
);

View file

@ -0,0 +1,65 @@
// The five document definitions (crates/thing-contract/src/lib.rs). `type` and `schemaVersion` are the crate's
// cultcache(type, schema). The codec runs on both doors (encodeDocumentPayload and decodeDocumentPayload run it and then
// the definition's schema.parse), so the domains hold whichever way a value enters. The four plain kinds parse as the
// identity; a command_result parses only an instance of CommandResult.
import { defineDocumentRegistry, defineDocumentType } from "@gamecult/cultcache-ts";
import { assetCatalog, commandInvocation, compositionDocument as compositionCodec, surfaceDocument as surfaceCodec } from "./codecs.js";
import { CommandResult, commandResult as commandResultCodec } from "./result.js";
import type { AssetCatalog, CommandInvocation, CompositionDocument, SurfaceDocument } from "./types.js";
const identity = <TValue>(input: unknown): TValue => input as TValue;
export const surfaceDocument = defineDocumentType({
type: "gamecult.thing.surface",
schemaName: "gamecult.thing.surface",
schemaVersion: "gamecult.thing.surface.v1",
schema: { parse: identity<SurfaceDocument> },
codec: surfaceCodec,
});
export const compositionDocument = defineDocumentType({
type: "gamecult.thing.composition",
schemaName: "gamecult.thing.composition",
schemaVersion: "gamecult.thing.composition.v1",
schema: { parse: identity<CompositionDocument> },
codec: compositionCodec,
});
export const commandInvocationDocument = defineDocumentType({
type: "gamecult.thing.command_invocation",
schemaName: "gamecult.thing.command_invocation",
schemaVersion: "gamecult.thing.command_invocation.v1",
schema: { parse: identity<CommandInvocation> },
codec: commandInvocation,
});
export const commandResultDocument = defineDocumentType({
type: "gamecult.thing.command_result",
schemaName: "gamecult.thing.command_result",
schemaVersion: "gamecult.thing.command_result.v1",
schema: {
parse(input: unknown): CommandResult {
if (!CommandResult.isResult(input)) throw new Error("a CommandResult is built by its factories");
return input;
},
},
codec: commandResultCodec,
});
export const assetCatalogDocument = defineDocumentType({
type: "gamecult.thing.asset_catalog",
schemaName: "gamecult.thing.asset_catalog",
schemaVersion: "gamecult.thing.asset_catalog.v1",
schema: { parse: identity<AssetCatalog> },
codec: assetCatalog,
});
/** The five kinds, as the crate's ThingContract registers them. */
export const thingContract = defineDocumentRegistry(
surfaceDocument,
compositionDocument,
commandInvocationDocument,
commandResultDocument,
assetCatalogDocument,
);

View file

@ -0,0 +1,82 @@
// The value domains of the contract's numbers and local names (crates/thing-contract/src/domain.rs). Each is a leaf
// codec of cultcache-ts with the contract's bound added, so the bound holds on both doors of a document: encode and
// decode. A refusal names the domain and its bound, never the value (the leaf's own refusals do not echo one either).
import { codecs } from "@gamecult/cultcache-ts";
import type { Codec, SlotsCodec } from "@gamecult/cultcache-ts";
// A domain's wire form is its value, so its encode hands the checked value back: a caller that holds a number from
// outside (a factory argument, a key part) passes it through `encode` and keeps what comes out.
export interface Domain<TValue> extends Codec<TValue> {
encode(value: TValue): TValue;
}
function bounded<TValue extends number | bigint | string>(
leaf: Codec<TValue>,
refusal: (value: TValue) => string | null,
): Domain<TValue> {
const hold = (value: TValue): TValue => {
const refused = refusal(value);
if (refused !== null) throw new Error(refused);
return value;
};
return {
typeName: leaf.typeName,
valueType: leaf.valueType,
encode: (value) => hold(leaf.encode(value) as TValue),
decode: (raw) => hold(leaf.decode(raw)),
};
}
/** A result's position in its invocation's answers, counting from 1. */
export const seq = bounded(codecs.int32, (value) => (value >= 1 ? null : "Seq must be at least 1"));
/** A document or source version, never negative. */
export const version = bounded(codecs.int64, (value) => (value >= 0 ? null : "Version must be at least 0"));
/** A count, an extent or an index, never negative. */
export const count = bounded(codecs.int32, (value) => (value >= 0 ? null : "Count must be at least 0"));
/**
* A name the contract joins into a record key: non-empty, no '.'. A domain admits no nil, and the library refuses a nil
* in a value slot, so it is declared one.
*/
export const segment: Domain<string> = {
...bounded(codecs.string, (value) =>
value === "" ? "Segment must be non-empty" : value.includes(".") ? "Segment must be free of '.'" : null,
),
valueType: true,
};
/** One colour channel: a byte. */
export const channel = bounded(codecs.int32, (value) => (value >= 0 && value <= 255 ? null : "Rgba channel must be 0 to 255"));
/**
* A slot the Rust type does not make optional. cultcache-ts reads nil in a string, bytes, record, list or union slot as
* null (the reference's leaf rule), so the slot codec is declared a value type, which makes the library hand it the nil,
* and a nil is refused here on decode and a null or undefined on encode. Typed names and the slots of a record pass
* through. The refusal names the domain, never the value; the library's slot path locates it.
*/
export function present<TValue extends object>(codec: SlotsCodec<TValue>): SlotsCodec<TValue>;
export function present<TValue>(codec: Codec<TValue | null>): Codec<TValue>;
export function present(codec: Codec<unknown>): Codec<unknown> {
const hold = (value: unknown): void => {
if (value === null || value === undefined) throw new Error("Presence: the slot is required");
};
const held: Codec<unknown> = {
get typeName() {
return codec.typeName;
},
valueType: true,
encode: (value) => (hold(value), codec.encode(value)),
decode: (raw) => (hold(raw), codec.decode(raw)),
};
if (!("names" in codec)) return held;
const record = codec as SlotsCodec<object>;
return Object.defineProperties(held, {
names: { get: () => record.names },
members: { get: () => record.members },
});
}
/** A required string: the string slot of a record whose Rust member is not an Option. */
export const text: Codec<string> = present(codecs.string);

View file

@ -0,0 +1,6 @@
export * as codecs from "./codecs.js";
export * as domain from "./domain.js";
export * from "./documents.js";
export * from "./keys.js";
export { CommandResult } from "./result.js";
export type * from "./types.js";

View file

@ -0,0 +1,25 @@
// The record key of each kind (crates/thing-contract/src/keys.rs). Provider, publisher and invocation ids are free
// strings (dotted, as the Verse names them); the trailing parts are typed, so a key splits at its last dot (surface,
// asset catalog, result) or last two (composition) and two different field sets never build one key. Each local
// segment goes through the segment codec, and a seq or version through its own.
import { segment, seq, version } from "./domain.js";
export function surfaceKey(providerId: string, label: string): string {
return `thing:surface:${providerId}.${segment.encode(label)}`;
}
export function compositionKey(publisher: string, name: string, versionNumber: number | bigint): string {
return `thing:composition:${publisher}.${segment.encode(name)}.v${version.encode(versionNumber)}`;
}
export function invocationKey(invocationId: string): string {
return `thing:invocation:${invocationId}`;
}
export function resultKey(invocationId: string, position: number): string {
return `thing:result:${invocationId}.${seq.encode(position)}`;
}
export function assetCatalogKey(providerId: string, catalogId: string): string {
return `thing:asset_catalog:${providerId}.${segment.encode(catalogId)}`;
}

View file

@ -0,0 +1,101 @@
// The answer to a command invocation. A CommandResult is built by its four factories, each of which copies the
// invocation's id, and by the command_result document codec when it decodes. Both doors go through `mint`, which runs
// the slot record on the three fields (presence, Seq, Version, the booleans: every check the decode door runs) and
// builds the instance from the copy that came out, so the value core validates is the value it holds: the outcome and
// its effect are frozen deep, and nothing the caller kept points into them. No export takes a state as a string or
// converts a plain object: an object literal, a spread, structuredClone copy or parsed JSON is not a result, and
// encoding one is refused (schema.parse in documents.ts).
//
// The copied invocation id is a convenience and not provenance: core binds a result to an invocation it issued.
import { codecs } from "@gamecult/cultcache-ts";
import type { SlotsCodec } from "@gamecult/cultcache-ts";
import { outcome } from "./codecs.js";
import { seq, text } from "./domain.js";
import type { CommandInvocation, Effect, NodeId, Outcome } from "./types.js";
// The one constructor call. The class's static block sets `mint`; the factories and the codec below use it; it is not
// exported. The constructor refuses a call that does not carry `door`, so a script that reaches the constructor at run
// time (the TypeScript `private` is compile-time only) builds nothing.
function freezeDeep<TValue>(value: TValue): TValue {
if (typeof value === "object" && value !== null) {
for (const member of Object.values(value)) freezeDeep(member);
Object.freeze(value);
}
return value;
}
const door: unique symbol = Symbol("CommandResult.door");
let mint: (invocationId: string, position: number, outcome: Outcome) => CommandResult;
export class CommandResult {
readonly #brand = true;
readonly invocationId: string;
readonly seq: number;
readonly outcome: Outcome;
private constructor(key: typeof door, invocationId: string, position: number, outcome: Outcome) {
if (key !== door) throw new Error("a CommandResult is built by its factories");
this.invocationId = invocationId;
this.seq = position;
this.outcome = outcome;
Object.freeze(this);
}
static {
// The slot record's wire form is a copy, so what is built is what was checked, and nothing the caller holds points
// into it.
mint = (invocationId, position, answer) => {
const checked = slotRecord.decode(slotRecord.encode({ invocationId, seq: position, outcome: answer }));
return new CommandResult(door, checked.invocationId, checked.seq, freezeDeep(checked.outcome));
};
}
static pending(invocation: CommandInvocation, position: number, message: string): CommandResult {
return mint(invocation.invocationId, position, { kind: "Pending", message });
}
static completed(
invocation: CommandInvocation,
position: number,
sourceVersion: number | bigint | null,
clearDrafts: boolean,
effect: Effect | null,
): CommandResult {
return mint(invocation.invocationId, position, { kind: "Completed", sourceVersion, clearDrafts, effect });
}
static denied(invocation: CommandInvocation, position: number, reason: string, node: NodeId | null): CommandResult {
return mint(invocation.invocationId, position, { kind: "Denied", reason, node });
}
static failed(invocation: CommandInvocation, position: number, reason: string): CommandResult {
return mint(invocation.invocationId, position, { kind: "Failed", reason });
}
/** True for an instance a factory or the codec made; false for every other value, whatever its shape or prototype. */
static isResult(value: unknown): value is CommandResult {
return typeof value === "object" && value !== null && #brand in value;
}
}
// The command_result document codec: the slot record, with decode minting an instance. Encode reads the instance's
// fields through the same slot record, so the domains are held on both doors, and so is mint.
const slotRecord = codecs.slots<{ invocationId: string; seq: number; outcome: Outcome }>(
{ 0: ["invocationId", text], 1: ["seq", seq], 2: ["outcome", outcome] },
"GameCult.Thing.Contract.CommandResult",
);
export const commandResult: SlotsCodec<CommandResult> = {
names: slotRecord.names,
typeName: slotRecord.typeName,
get members() {
return slotRecord.members;
},
encode: (value) => slotRecord.encode(value),
decode: (raw) => {
const { invocationId, seq: position, outcome: answer } = slotRecord.decode(raw);
return mint(invocationId, position, answer);
},
};

View file

@ -0,0 +1,378 @@
// One TypeScript type per type of crates/thing-contract. A record is an interface of readonly camelCase fields; a closed
// set is a union discriminated on `kind`, the Rust arm name, and an arm carries its payload's fields beside the tag (a
// unit arm is just the tag). Option<T> is `T | null`, Vec<T> is `readonly T[]`, bytes are a Uint8Array.
//
// The value domains (Seq, Version, Count, Segment, an Rgba channel) are held by the codecs in domain.ts, not by these
// types: a type cannot say "at least 1". Every document is minted and checked by its codec.
type Arm<Kind extends string, Payload = unknown> = { readonly kind: Kind } & Payload;
export type ProviderId = string;
export type SchemaId = string;
export type RecordKey = string;
export type NodeId = string;
export type CommandId = string;
// source.rs
export interface ParamName { readonly name: string }
export interface TextLiteral { readonly value: string }
export interface NumberLiteral { readonly value: number }
export interface BoolLiteral { readonly value: boolean }
export type TextSource = Arm<"Literal", TextLiteral> | Arm<"Bound", Bind> | Arm<"Param", ParamName>;
export type NumberSource = Arm<"Literal", NumberLiteral> | Arm<"Bound", Bind> | Arm<"Param", ParamName>;
export type BoolSource = Arm<"Literal", BoolLiteral> | Arm<"Bound", Bind> | Arm<"Param", ParamName>;
export interface Bind {
readonly source: StateSource;
readonly member: MemberPath;
readonly format: Format | null;
}
export type StateSource = Arm<"Record", StateRef> | Arm<"Item">;
export interface StateRef {
readonly provider: ProviderId | null;
readonly schema: SchemaId;
readonly key: RecordKey;
}
export interface MemberPath { readonly steps: readonly MemberStep[] }
export type MemberStep = Arm<"Name", MemberName> | Arm<"Index", MemberIndex>;
export interface MemberName { readonly name: string }
/** `index` is a Count: at least 0. */
export interface MemberIndex { readonly index: number }
export type Format = Arm<"Number", NumberFormat> | Arm<"Duration"> | Arm<"Timestamp"> | Arm<"Affix", AffixFormat>;
/** `precision` is a Count: at least 0. */
export interface NumberFormat {
readonly precision: number;
readonly percent: boolean;
readonly unit: string | null;
}
export interface AffixFormat { readonly prefix: string; readonly suffix: string }
export type CollectionSource = Arm<"Records", RecordsSource> | Arm<"Member", Bind> | Arm<"Param", ParamName>;
export interface RecordsSource {
readonly provider: ProviderId | null;
readonly schema: SchemaId;
readonly keyPrefix: string;
}
// style.rs
export interface Scalar { readonly value: number }
export type Dimension =
| Arm<"Px", Scalar>
| Arm<"Percent", Scalar>
| Arm<"Fr", Scalar>
| Arm<"Auto">
| Arm<"Content">;
export interface Size2 { readonly width: Dimension; readonly height: Dimension }
export interface Edges {
readonly top: Dimension;
readonly right: Dimension;
readonly bottom: Dimension;
readonly left: Dimension;
}
export type Display = Arm<"Flex"> | Arm<"Grid"> | Arm<"Block">;
export type Direction = Arm<"Row"> | Arm<"Column"> | Arm<"RowReverse"> | Arm<"ColumnReverse">;
export type Wrap = Arm<"NoWrap"> | Arm<"Wrap"> | Arm<"WrapReverse">;
export type Position = Arm<"Relative"> | Arm<"Absolute">;
export type Overflow = Arm<"Visible"> | Arm<"Clip"> | Arm<"Scroll">;
export type ItemAlign = Arm<"Auto"> | Arm<"Start"> | Arm<"End"> | Arm<"Center"> | Arm<"Stretch"> | Arm<"Baseline">;
export type ContentAlign =
| Arm<"Auto">
| Arm<"Start">
| Arm<"End">
| Arm<"Center">
| Arm<"Stretch">
| Arm<"SpaceBetween">
| Arm<"SpaceAround">
| Arm<"SpaceEvenly">;
export interface BoxStyle {
readonly display: Display;
readonly direction: Direction;
readonly wrap: Wrap;
readonly gap: Size2;
readonly padding: Edges;
readonly margin: Edges;
readonly size: Size2;
readonly minSize: Size2;
readonly maxSize: Size2;
readonly position: Position;
readonly inset: Edges;
readonly overflow: Overflow;
readonly alignItems: ItemAlign;
readonly alignSelf: ItemAlign;
readonly alignContent: ContentAlign;
readonly justifyContent: ContentAlign;
readonly grow: number;
readonly shrink: number;
readonly basis: Dimension;
readonly gridColumns: readonly Dimension[];
readonly gridRows: readonly Dimension[];
}
export interface ThemeToken { readonly name: string }
/** Each channel is a byte: 0 to 255. */
export interface Rgba { readonly r: number; readonly g: number; readonly b: number; readonly a: number }
export type ColorRef = Arm<"Token", ThemeToken> | Arm<"Rgba", Rgba>;
export interface Border { readonly color: ColorRef; readonly width: number }
export interface Paint {
readonly background: ColorRef | null;
readonly border: Border | null;
readonly radius: number;
}
export type Role =
| Arm<"Group">
| Arm<"Region">
| Arm<"List">
| Arm<"ListItem">
| Arm<"Heading">
| Arm<"Dialog">
| Arm<"Toolbar">;
// command.rs
export interface CommandDecl {
readonly id: CommandId;
readonly payloadSchema: SchemaId;
readonly captures: readonly NodeId[];
readonly confirm: string | null;
}
export interface CommandIdRef { readonly id: CommandId }
export type CommandRef = Arm<"Id", CommandIdRef> | Arm<"Param", ParamName>;
export interface RecordPayload { readonly schema: SchemaId; readonly bytes: Uint8Array }
export interface TextValue { readonly value: string }
export interface NumberValue { readonly value: number }
export interface BoolValue { readonly value: boolean }
export interface ChoiceValue { readonly value: string }
export type InputValue = Arm<"Text", TextValue> | Arm<"Number", NumberValue> | Arm<"Bool", BoolValue> | Arm<"Choice", ChoiceValue>;
export interface CapturedInput { readonly node: NodeId; readonly value: InputValue }
/**
* A consumer's request that a provider run a declared command. Its fields are plain, so a result's copy of
* `invocationId` is a convenience and not provenance: core binds results to the invocations it issued.
* `surfaceVersion` is a Version: at least 0.
*/
export interface CommandInvocation {
readonly invocationId: string;
readonly surfaceKey: string;
readonly surfaceVersion: number | bigint;
readonly command: CommandId;
readonly payload: RecordPayload;
readonly captured: readonly CapturedInput[];
readonly client: string;
readonly issuedAt: string;
readonly delegation: string | null;
}
// result.rs
export interface PendingOutcome { readonly message: string }
/** `sourceVersion` is a Version: at least 0. */
export interface CompletedOutcome {
readonly sourceVersion: number | bigint | null;
readonly clearDrafts: boolean;
readonly effect: Effect | null;
}
export interface DeniedOutcome { readonly reason: string; readonly node: NodeId | null }
export interface FailedOutcome { readonly reason: string }
export type Outcome =
| Arm<"Pending", PendingOutcome>
| Arm<"Completed", CompletedOutcome>
| Arm<"Denied", DeniedOutcome>
| Arm<"Failed", FailedOutcome>;
export interface OpenSurfaceEffect { readonly key: string }
export interface OpenExternalEffect { readonly url: string; readonly resume: CommandRef }
export type Effect = Arm<"OpenSurface", OpenSurfaceEffect> | Arm<"OpenExternal", OpenExternalEffect>;
/** A provider's handler for one invocation: the outcome it answers with. */
export type Handler = (invocation: CommandInvocation) => Outcome | Promise<Outcome>;
// node.rs
export interface NodeCommon {
readonly id: NodeId;
readonly visible: BoolSource;
readonly a11yLabel: TextSource | null;
}
export type Node =
| Arm<"Box", BoxNode>
| Arm<"Text", TextNode>
| Arm<"Image", ImageNode>
| Arm<"Button", ButtonNode>
| Arm<"Toggle", ToggleNode>
| Arm<"Slider", SliderNode>
| Arm<"TextInput", TextInputNode>
| Arm<"Select", SelectNode>
| Arm<"Repeat", RepeatNode>
| Arm<"Overlay", OverlayNode>
| Arm<"Plot", PlotNode>
| Arm<"Embed", EmbedNode>
| Arm<"Use", UseNode>
| Arm<"Slot", SlotNode>;
/**
* Where a composition body places the nodes passed for its Slot parameter `param`. Only a child list of a composition
* body holds one, and resolve refuses it elsewhere. It carries no NodeCommon: the argument's nodes, keeping their
* caller-scope ids, replace it.
*/
export interface SlotNode {
readonly param: ParamName;
}
export interface BoxNode {
readonly common: NodeCommon;
readonly style: BoxStyle;
readonly paint: Paint;
readonly role: Role;
readonly children: readonly Node[];
}
/** `maxLines` is a Count: at least 0. */
export interface TextNode {
readonly common: NodeCommon;
readonly content: TextSource;
readonly styleToken: string;
readonly wrap: boolean;
readonly maxLines: number | null;
readonly selectable: boolean;
}
export type ImageFit = Arm<"Contain"> | Arm<"Cover"> | Arm<"Fill"> | Arm<"Unscaled">;
export interface ImageNode {
readonly common: NodeCommon;
readonly catalog: string;
readonly asset: string;
readonly fit: ImageFit;
readonly alt: TextSource;
}
export interface ButtonNode {
readonly common: NodeCommon;
readonly content: readonly Node[];
readonly onActivate: CommandRef;
readonly enabled: BoolSource;
}
export interface ToggleNode {
readonly common: NodeCommon;
readonly checked: BoolSource;
readonly onChange: CommandRef;
}
export interface SliderNode {
readonly common: NodeCommon;
readonly min: number;
readonly max: number;
readonly step: number;
readonly value: NumberSource;
readonly commit: CommandRef;
}
export type InputKind = Arm<"Text"> | Arm<"Number">;
/**
* The C# member is InputKind, the camelCase of the Rust field `input_kind`; the name is not a divergence. It could not be
* `kind`, which a TextInput arm's payload would share with the union's own `kind` tag.
*/
export interface TextInputNode {
readonly common: NodeCommon;
readonly multiline: boolean;
readonly inputKind: InputKind;
readonly placeholder: TextSource;
readonly initial: TextSource;
readonly submit: CommandRef;
}
export interface SelectOption { readonly value: string; readonly label: string }
export interface LiteralOptions { readonly options: readonly SelectOption[] }
export interface BoundOptions {
readonly collection: CollectionSource;
readonly valueMember: MemberPath;
readonly labelMember: MemberPath;
}
export type OptionList = Arm<"Literal", LiteralOptions> | Arm<"Bound", BoundOptions>;
export interface SelectNode {
readonly common: NodeCommon;
readonly options: OptionList;
readonly value: Bind;
readonly onChange: CommandRef;
}
export interface RepeatNode {
readonly common: NodeCommon;
readonly collection: CollectionSource;
readonly keyMember: MemberPath;
readonly template: Node;
}
export interface AnchorNode { readonly node: NodeId }
export type Anchor = Arm<"Viewport"> | Arm<"Node", AnchorNode>;
export interface OverlayNode {
readonly common: NodeCommon;
readonly anchor: Anchor;
readonly modal: boolean;
readonly dismiss: CommandRef;
readonly children: readonly Node[];
}
export type PlotMark = Arm<"Line"> | Arm<"Bar"> | Arm<"Area">;
export interface PlotNode {
readonly common: NodeCommon;
readonly series: Bind;
readonly mark: PlotMark;
readonly xMin: number | null;
readonly xMax: number | null;
readonly yMin: number | null;
readonly yMax: number | null;
}
export interface EmbedNode {
readonly common: NodeCommon;
readonly slotKind: string;
readonly slotId: string;
readonly width: number;
readonly height: number;
}
/** `name` is a Segment (non-empty, no '.'); `version` is a Version (at least 0). */
export interface CompositionRef {
readonly publisher: string;
readonly name: string;
readonly version: number | bigint;
}
export interface UseNode {
readonly common: NodeCommon;
readonly composition: CompositionRef;
readonly args: readonly Arg[];
}
export interface Arg { readonly name: string; readonly value: ArgValue }
export interface TextArg { readonly value: string }
export interface NumberArg { readonly value: number }
export interface BoolArg { readonly value: boolean }
export interface CollectionArg { readonly source: CollectionSource }
export interface CommandArg { readonly command: CommandRef }
export interface SlotArg { readonly nodes: readonly Node[] }
export type ArgValue =
| Arm<"Text", TextArg>
| Arm<"Number", NumberArg>
| Arm<"Bool", BoolArg>
| Arm<"Bind", Bind>
| Arm<"Collection", CollectionArg>
| Arm<"Command", CommandArg>
| Arm<"Slot", SlotArg>;
export type ParamKind =
| Arm<"Text">
| Arm<"Number">
| Arm<"Bool">
| Arm<"Bind">
| Arm<"Collection">
| Arm<"Command">
| Arm<"Slot">;
export interface ParamDecl { readonly name: string; readonly kind: ParamKind }
// The documents. `label`, `name` and `catalogId` are Segments, `version` a Version, an extent a Count. The fifth
// document, CommandResult, is a class (result.ts).
export interface SurfaceDocument {
readonly providerId: ProviderId;
readonly label: string;
readonly version: number | bigint;
readonly title: string;
readonly root: Node;
readonly commands: readonly CommandDecl[];
}
export interface CompositionDocument {
readonly publisher: string;
readonly name: string;
readonly version: number | bigint;
readonly params: readonly ParamDecl[];
readonly body: Node;
}
export interface AssetEntry {
readonly id: string;
readonly mediaType: string;
readonly uri: string;
readonly width: number;
readonly height: number;
}
export interface AssetCatalog {
readonly providerId: ProviderId;
readonly catalogId: string;
readonly version: number | bigint;
readonly assets: readonly AssetEntry[];
}

View file

@ -0,0 +1,489 @@
// The values the goldens are built from, ported from crates/thing-contract/tests/common/mod.rs and goldens.rs. Every
// value is an object literal of the package's exported types; no bytes are spelled here. The golden files are read, never
// written: the Rust crate blesses them.
import { existsSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { CommandResult } from "@gamecult/thing-contract";
import type {
Arg,
AssetCatalog,
BoxNode,
Bind,
BoolSource,
CollectionSource,
CommandInvocation,
CommandRef,
CompositionDocument,
Dimension,
Edges,
Format,
MemberPath,
Node,
NodeCommon,
NumberSource,
Paint,
Size2,
SurfaceDocument,
TextSource,
BoxStyle,
} from "@gamecult/thing-contract";
export const CANARY = "CANARY-7f3a91c2";
export const PINNED_CLOCK = "2026-01-01T00:00:00Z";
/** The nearest ancestor of this file that holds `relative` (a mutation sandbox sits deeper in the tree). */
function above(relative: string[], what: string): string {
let here = dirname(fileURLToPath(import.meta.url));
for (;;) {
const candidate = join(here, ...relative);
if (existsSync(candidate)) return candidate;
const parent = dirname(here);
if (parent === here) throw new Error(`${what} is not above this file`);
here = parent;
}
}
/** The Rust crate's goldens directory. */
export const goldensDir: string = above(["crates", "thing-contract", "tests", "goldens"], "the Rust crate's goldens directory");
/** The C# package's name set and the fixtures each package writes for the other. */
export const parityDir: string = above(["tests", "thing-contract-parity"], "the parity directory");
/** The lines of a file of the C# package's name set, or the rows of a tsv (cells split on tab). */
export function nonEmptyLines(path: string): string[] {
return readFileSync(path, "utf8").split(/\r?\n/).filter((line) => line.length > 0);
}
export function golden(file: string): Uint8Array {
return new Uint8Array(readFileSync(join(goldensDir, file)));
}
export const lit = (value: string): TextSource => ({ kind: "Literal", value });
export const litBool = (value: boolean): BoolSource => ({ kind: "Literal", value });
export const litNumber = (value: number): NumberSource => ({ kind: "Literal", value });
export const param = (name: string) => ({ kind: "Param", name }) as const;
export const path = (...names: string[]): MemberPath => ({ steps: names.map((name) => ({ kind: "Name", name }) as const) });
export const command = (id: string): CommandRef => ({ kind: "Id", id });
export function recordBind(member: MemberPath, format: Format | null): Bind {
return {
source: { kind: "Record", provider: "provider.a", schema: "gamecult.thing.test.v1", key: "row-1" },
member,
format,
};
}
export const itemBind = (member: MemberPath): Bind => ({ source: { kind: "Item" }, member, format: null });
export const common = (id: string): NodeCommon => ({ id, visible: litBool(true), a11yLabel: null });
export const px = (value: number): Dimension => ({ kind: "Px", value });
export const size2 = (width: Dimension, height: Dimension): Size2 => ({ width, height });
export const edges = (all: Dimension): Edges => ({ top: all, right: all, bottom: all, left: all });
export function style(): BoxStyle {
return {
display: { kind: "Flex" },
direction: { kind: "Column" },
wrap: { kind: "NoWrap" },
gap: size2(px(4), px(8)),
padding: edges(px(2)),
margin: edges({ kind: "Auto" }),
size: size2({ kind: "Percent", value: 100 }, { kind: "Content" }),
minSize: size2(px(0), px(0)),
maxSize: size2({ kind: "Auto" }, { kind: "Auto" }),
position: { kind: "Relative" },
inset: edges({ kind: "Auto" }),
overflow: { kind: "Visible" },
alignItems: { kind: "Stretch" },
alignSelf: { kind: "Auto" },
alignContent: { kind: "Start" },
justifyContent: { kind: "SpaceBetween" },
grow: 1,
shrink: 0,
basis: { kind: "Auto" },
gridColumns: [],
gridRows: [],
};
}
export const plainPaint = (): Paint => ({ background: null, border: null, radius: 0 });
export function boxNode(id: string, children: readonly Node[]): BoxNode {
return { common: common(id), style: style(), paint: plainPaint(), role: { kind: "Group" }, children };
}
export const boxed = (id: string, children: readonly Node[]): Node => ({ kind: "Box", ...boxNode(id, children) });
export const text = (id: string, content: string): Node => ({
kind: "Text",
common: common(id),
content: lit(content),
styleToken: "body",
wrap: true,
maxLines: null,
selectable: false,
});
export function invocation(): CommandInvocation {
return {
invocationId: "3f2b8c1e-5d44-4a6b-9a07-1c2d3e4f5a6b",
surfaceKey: "thing:surface:provider.a.main",
surfaceVersion: 7,
command: "go",
payload: { schema: "gamecult.thing.test.go.v1", bytes: new Uint8Array([0x91, 0x01, 0xff, 0x00]) },
captured: [
{ node: "name-input", value: { kind: "Text", value: "Ada" } },
{ node: "level", value: { kind: "Number", value: 0.75 } },
{ node: "flag", value: { kind: "Bool", value: true } },
{ node: "pick", value: { kind: "Choice", value: "a" } },
],
client: "renderer.web",
issuedAt: PINNED_CLOCK,
delegation: "delegate-1",
};
}
export function bindAllFormats(): Bind[] {
const number: Format = { kind: "Number", precision: 2, percent: true, unit: "ms" };
const affix: Format = { kind: "Affix", prefix: "$", suffix: "/s" };
const indexed: MemberPath = { steps: [{ kind: "Name", name: "items" }, { kind: "Index", index: 3 }] };
return [
recordBind(indexed, number),
recordBind(path("elapsed"), { kind: "Duration" }),
recordBind(path("at"), { kind: "Timestamp" }),
recordBind(path("price"), affix),
recordBind(path("plain"), null),
itemBind(path("name")),
];
}
export function fullSurface(): SurfaceDocument {
const binds = bindAllFormats();
const boundText: TextSource = { kind: "Bound", ...binds[3] };
const boundBool: BoolSource = { kind: "Bound", ...binds[4] };
const boundNumber: NumberSource = { kind: "Bound", ...binds[0] };
const painted: Node = {
kind: "Box",
common: { id: "painted", visible: param("show"), a11yLabel: param("label") },
style: {
...style(),
display: { kind: "Grid" },
gridColumns: [{ kind: "Fr", value: 1 }, px(120)],
gridRows: [{ kind: "Content" }],
position: { kind: "Absolute" },
overflow: { kind: "Scroll" },
direction: { kind: "RowReverse" },
wrap: { kind: "WrapReverse" },
alignItems: { kind: "Baseline" },
alignSelf: { kind: "Center" },
alignContent: { kind: "SpaceAround" },
justifyContent: { kind: "SpaceEvenly" },
},
paint: {
background: { kind: "Token", name: "surface.raised" },
border: { color: { kind: "Rgba", r: 1, g: 2, b: 3, a: 255 }, width: 1.5 },
radius: 4,
},
role: { kind: "Region" },
children: [text("deep-text", "deep")],
};
const repeat: Node = {
kind: "Repeat",
common: common("rows"),
collection: { kind: "Records", provider: null, schema: "gamecult.thing.test.v1", keyPrefix: "row-" },
keyMember: path("id"),
template: {
kind: "Text",
common: common("row-name"),
content: { kind: "Bound", ...itemBind(path("name")) },
styleToken: "body",
wrap: false,
maxLines: 2,
selectable: true,
},
};
const leaves: Node[] = [
{
kind: "Text",
common: common("t-bound"),
content: boundText,
styleToken: "label",
wrap: true,
maxLines: null,
selectable: false,
},
{ kind: "Image", common: common("img"), catalog: "icons", asset: "gear", fit: { kind: "Cover" }, alt: lit("a gear") },
{
kind: "Button",
common: common("go"),
content: [text("go-label", "Go")],
onActivate: command("go"),
enabled: boundBool,
},
{ kind: "Toggle", common: common("flag"), checked: boundBool, onChange: param("toggle") },
{
kind: "Slider",
common: common("level"),
min: 0,
max: 1,
step: 0.25,
value: boundNumber,
commit: command("set-level"),
},
{
kind: "TextInput",
common: common("name-input"),
multiline: true,
inputKind: { kind: "Number" },
placeholder: lit("name"),
initial: param("initial"),
submit: command("rename"),
},
{
kind: "TextInput",
common: common("title-input"),
multiline: false,
inputKind: { kind: "Text" },
placeholder: lit("title"),
initial: param("initial"),
submit: command("retitle"),
},
{
kind: "Select",
common: common("pick"),
options: { kind: "Literal", options: [{ value: "a", label: "Alpha" }] },
value: binds[4],
onChange: command("pick"),
},
{
kind: "Select",
common: common("pick-bound"),
options: {
kind: "Bound",
collection: { kind: "Member", ...binds[0] },
valueMember: path("id"),
labelMember: path("name"),
},
value: binds[5],
onChange: command("pick"),
},
repeat,
{
kind: "Overlay",
common: common("menu"),
anchor: { kind: "Node", node: "go" },
modal: false,
dismiss: command("close"),
children: [text("menu-item", "one")],
},
{
kind: "Overlay",
common: common("dialog"),
anchor: { kind: "Viewport" },
modal: true,
dismiss: command("close"),
children: [],
},
{
kind: "Plot",
common: common("trend"),
series: binds[1],
mark: { kind: "Area" },
xMin: 0,
xMax: null,
yMin: null,
yMax: 100,
},
{ kind: "Embed", common: common("viewport"), slotKind: "world.scene", slotId: "main", width: 640, height: 480 },
{
kind: "Use",
common: common("kv"),
composition: { publisher: "thing.std", name: "key-value", version: 1 },
args: [{ name: "key", value: { kind: "Text", value: "k" } }],
},
];
let deep: Node = boxed("d4", [painted]);
for (const id of ["d3", "d2", "d1"]) deep = boxed(id, [deep]);
const children: Node[] = [deep, ...leaves];
for (const [id, mark] of [
["trend-line", { kind: "Line" }],
["trend-bar", { kind: "Bar" }],
] as const) {
children.push({
kind: "Plot",
common: common(id),
series: binds[2],
mark,
xMin: null,
xMax: null,
yMin: null,
yMax: null,
});
}
(["Contain", "Fill", "Unscaled"] as const).forEach((fit, index) => {
children.push({
kind: "Image",
common: common(`img-fit-${index}`),
catalog: "icons",
asset: "gear",
fit: { kind: fit },
alt: lit(""),
});
});
(["List", "ListItem", "Heading", "Dialog", "Toolbar"] as const).forEach((role, index) => {
const roleStyle: BoxStyle =
index === 0
? { ...style(), direction: { kind: "Row" }, alignContent: { kind: "Auto" }, justifyContent: { kind: "Stretch" } }
: style();
children.push({
kind: "Box",
common: common(`role-${index}`),
style: roleStyle,
paint: plainPaint(),
role: { kind: role },
children: [],
});
});
children.push({
kind: "Box",
common: common("block"),
style: {
...style(),
display: { kind: "Block" },
direction: { kind: "ColumnReverse" },
wrap: { kind: "Wrap" },
overflow: { kind: "Clip" },
alignContent: { kind: "Center" },
justifyContent: { kind: "End" },
alignItems: { kind: "End" },
alignSelf: { kind: "Start" },
basis: { kind: "Content" },
},
paint: plainPaint(),
role: { kind: "Group" },
children: [],
});
children.push({
kind: "Text",
common: common("t-param"),
content: param("title"),
styleToken: "title",
wrap: true,
maxLines: null,
selectable: false,
});
children.push({
kind: "Toggle",
common: { id: "literal-number", visible: param("v"), a11yLabel: null },
checked: litBool(false),
onChange: command("toggle"),
});
children.push({
kind: "Slider",
common: common("slider-literal"),
min: -1,
max: 1,
step: 0.5,
value: litNumber(0.5),
commit: command("set-level"),
});
children.push({
kind: "Slider",
common: common("slider-param"),
min: 0,
max: 10,
step: 1,
value: param("n"),
commit: command("set-level"),
});
const rows: CollectionSource = param("rows");
children.push({
kind: "Repeat",
common: common("rows-param"),
collection: rows,
keyMember: path("id"),
template: text("row-param", "r"),
});
return {
providerId: "provider.a",
label: "main",
version: 7,
title: "All arms",
root: boxed("root", children),
commands: [
{ id: "go", payloadSchema: "gamecult.thing.test.go.v1", captures: ["name-input", "level"], confirm: "Go now?" },
{ id: "close", payloadSchema: "gamecult.thing.test.close.v1", captures: [], confirm: null },
],
};
}
export function fullComposition(): CompositionDocument {
const args: Arg[] = [
{ name: "text", value: { kind: "Text", value: "t" } },
{ name: "number", value: { kind: "Number", value: 2.5 } },
{ name: "bool", value: { kind: "Bool", value: true } },
{ name: "bind", value: { kind: "Bind", ...recordBind(path("x"), null) } },
{ name: "collection", value: { kind: "Collection", source: param("rows") } },
{ name: "command", value: { kind: "Command", command: command("go") } },
{ name: "slot", value: { kind: "Slot", nodes: [text("slot-text", "inside"), boxed("slot-box", [])] } },
];
const innerUse: Node = {
kind: "Use",
common: common("inner"),
composition: { publisher: "thing.std", name: "card", version: 2 },
args,
};
return {
publisher: "provider.a",
name: "panel",
version: 3,
params: [
{ name: "title", kind: { kind: "Text" } },
{ name: "count", kind: { kind: "Number" } },
{ name: "on", kind: { kind: "Bool" } },
{ name: "source", kind: { kind: "Bind" } },
{ name: "rows", kind: { kind: "Collection" } },
{ name: "act", kind: { kind: "Command" } },
{ name: "body", kind: { kind: "Slot" } },
],
body: boxed("panel-root", [text("panel-title", "t"), innerUse, { kind: "Slot", param: { name: "body" } }]),
};
}
export function results(answered: CommandInvocation): [string, CommandResult][] {
return [
["result-pending", CommandResult.pending(answered, 1, "working")],
["result-completed", CommandResult.completed(answered, 2, 8, true, null)],
[
"result-completed-open-surface",
CommandResult.completed(answered, 3, null, false, { kind: "OpenSurface", key: "thing:surface:provider.a.next" }),
],
[
"result-completed-open-external",
CommandResult.completed(answered, 4, 9, true, {
kind: "OpenExternal",
url: "https://example.test/auth",
resume: command("resume"),
}),
],
["result-denied", CommandResult.denied(answered, 5, "not yours", "go")],
["result-denied-no-node", CommandResult.denied(answered, 6, "not allowed", null)],
["result-failed", CommandResult.failed(answered, 7, "broke")],
];
}
export function assetCatalogValue(): AssetCatalog {
return {
providerId: "provider.a",
catalogId: "icons",
version: 2,
assets: [
{ id: "gear", mediaType: "image/png", uri: "assets/gear.png", width: 32, height: 32 },
{ id: "bolt", mediaType: "image/svg+xml", uri: "assets/bolt.svg", width: 0, height: 0 },
],
};
}

View file

@ -0,0 +1,56 @@
// Every codec of the package is named by the C# package's name set (tests/thing-contract-parity/type-names.txt), and
// every union names itself in its refusals. The names are read, never restated here: the C# package owns them.
import assert from "node:assert/strict";
import { join } from "node:path";
import test from "node:test";
import { decodeDocumentPayload, documentPayloadFromBytes } from "@gamecult/cultcache-ts";
import { codecs, compositionDocument, type Node } from "@gamecult/thing-contract";
import { golden, nonEmptyLines, parityDir } from "./builders.js";
const entries = Object.entries(codecs) as [string, { typeName?: string; decode(raw: unknown): unknown }][];
const rustName = (key: string) => key[0].toUpperCase() + key.slice(1);
const names = new Set(nonEmptyLines(join(parityDir, "type-names.txt")));
test("the package exports one hundred and three codecs", () => {
assert.equal(entries.length, 103);
});
test("every codec's type name is a type of the C# package", () => {
for (const [key, codec] of entries) {
assert.ok(codec.typeName !== undefined && names.has(codec.typeName), `${key}: ${codec.typeName}`);
}
assert.equal(new Set(entries.map(([, codec]) => codec.typeName)).size, entries.length, "no two codecs share a name");
});
test("every union refuses an unknown arm by its own name, and the twenty-nine unions are all of them", () => {
const unions: string[] = [];
for (const [key, codec] of entries) {
let message: string;
try {
codec.decode([2 ** 30, []]);
continue;
} catch (error) {
message = (error as Error).message;
}
const named = /^Union (\w+): unknown arm key 1073741824 \(declared keys: [-\d, ]+\)\.$/.exec(message);
if (named === null) continue;
unions.push(key);
assert.equal(named[1], rustName(key), key);
}
assert.equal(unions.length, 29);
});
test("slot: a Slot is arm 13 holding a nested ParamName, and the composition golden places it last in the body root's children", () => {
const slot: Node = { kind: "Slot", param: { name: "body" } };
assert.deepEqual(codecs.node.encode(slot), [13, [["body"]]]);
assert.deepStrictEqual(codecs.node.decode([13, [["body"]]]), slot);
assert.throws(() => codecs.node.decode([13, ["body"]]));
assert.throws(() => codecs.node.decode([13, [[null]]]));
const decoded = decodeDocumentPayload(compositionDocument, documentPayloadFromBytes(golden("composition-all-params.bin")));
assert.equal(decoded.body.kind, "Box");
if (decoded.body.kind !== "Box") return;
assert.deepStrictEqual(decoded.body.children.at(-1), slot);
});

View file

@ -0,0 +1,76 @@
// The deepest tree the payload bound admits decodes and re-encodes on Node's default stack (no --stack-size), and one
// level deeper is refused with CultCachePayloadDepthError, never an abort. The Rust test of the same name holds on its
// default test thread too.
import assert from "node:assert/strict";
import test from "node:test";
import {
CultCachePayloadDepthError,
MAX_PAYLOAD_DEPTH,
decodeDocumentPayload,
documentPayloadBytes,
documentPayloadFromBytes,
encodeDocumentPayload,
} from "@gamecult/cultcache-ts";
import { surfaceDocument } from "@gamecult/thing-contract";
import type { Node, SurfaceDocument } from "@gamecult/thing-contract";
import { boxNode, boxed, text } from "./builders.js";
function chain(levels: number): SurfaceDocument {
let root: Node = text("leaf", "bottom");
for (let depth = levels - 1; depth >= 0; depth--) root = boxed(`deep-${depth}`, [root]);
return { providerId: "provider.a", label: "deep", version: 1, title: "deep", root, commands: [] };
}
const admits = (levels: number): boolean => {
try {
encodeDocumentPayload(surfaceDocument, chain(levels));
return true;
} catch (error) {
assert.ok(error instanceof CultCachePayloadDepthError, "the only refusal of a plain chain is the depth bound");
assert.equal(error.limit, MAX_PAYLOAD_DEPTH);
return false;
}
};
test("the deepest Box chain the bound admits round-trips on the default stack, and one more is refused", () => {
let deepest = 1;
while (admits(deepest + 1)) deepest++;
assert.equal(deepest, 83, "the bound admits 83 Box levels above the text leaf, 84 nodes deep");
assert.ok(!admits(deepest + 1));
const value = chain(deepest);
const bytes = documentPayloadBytes(encodeDocumentPayload(surfaceDocument, value));
const decoded = decodeDocumentPayload(surfaceDocument, documentPayloadFromBytes(bytes));
assert.deepStrictEqual(decoded, value);
assert.deepEqual(documentPayloadBytes(encodeDocumentPayload(surfaceDocument, decoded)), bytes);
});
test("a payload one container past the bound is refused with the depth error, before any codec reads it", () => {
const nested = (levels: number) => new Uint8Array([...new Array<number>(levels).fill(0x91), 0xc0]);
assert.throws(
() => decodeDocumentPayload(surfaceDocument, documentPayloadFromBytes(nested(MAX_PAYLOAD_DEPTH + 1))),
(error: unknown) => error instanceof CultCachePayloadDepthError && error.depth === MAX_PAYLOAD_DEPTH + 1,
);
// At the bound the walk admits it and the codec refuses the shape instead.
assert.throws(
() => decodeDocumentPayload(surfaceDocument, documentPayloadFromBytes(nested(MAX_PAYLOAD_DEPTH))),
(error: unknown) => error instanceof Error && !(error instanceof CultCachePayloadDepthError),
);
});
test("a wide tree of a thousand nodes round-trips", () => {
const children: Node[] = Array.from({ length: 998 }, (_, index) => text(`t${index}`, "x"));
children.push(boxed("tail", []));
const wide: SurfaceDocument = {
providerId: "provider.a",
label: "wide",
version: 1,
title: "wide",
root: { kind: "Box", ...boxNode("root", children) },
commands: [],
};
const bytes = documentPayloadBytes(encodeDocumentPayload(surfaceDocument, wide));
assert.deepStrictEqual(decodeDocumentPayload(surfaceDocument, documentPayloadFromBytes(bytes)), wide);
});

View file

@ -0,0 +1,75 @@
// The five definitions carry the crate's cultcache(type, schema) and, per document slot, the reference's member name
// and C# type name that a store's schema catalog is compared on. The members are read from the C# package's catalog
// (tests/thing-contract-parity/catalog-members.tsv), never restated here.
import assert from "node:assert/strict";
import { join } from "node:path";
import test from "node:test";
import {
assetCatalogDocument,
commandInvocationDocument,
commandResultDocument,
compositionDocument,
surfaceDocument,
thingContract,
} from "@gamecult/thing-contract";
import { nonEmptyLines, parityDir } from "./builders.js";
const NS = "GameCult.Thing.Contract.";
const rustName: Record<string, string> = {
"gamecult.thing.surface": "SurfaceDocument",
"gamecult.thing.composition": "CompositionDocument",
"gamecult.thing.command_invocation": "CommandInvocation",
"gamecult.thing.command_result": "CommandResult",
"gamecult.thing.asset_catalog": "AssetCatalog",
};
const definitions = [
[surfaceDocument, "gamecult.thing.surface"],
[compositionDocument, "gamecult.thing.composition"],
[commandInvocationDocument, "gamecult.thing.command_invocation"],
[commandResultDocument, "gamecult.thing.command_result"],
[assetCatalogDocument, "gamecult.thing.asset_catalog"],
] as const;
/** The catalog's rows grouped by C# schema id, each group as `slot:Member:TypeName` strings. */
function catalogGroups(): string[][] {
const groups = new Map<string, string[]>();
for (const row of nonEmptyLines(join(parityDir, "catalog-members.tsv"))) {
const [schemaId, slot, member, typeName] = row.split("\t");
groups.set(schemaId, [...(groups.get(schemaId) ?? []), `${slot}:${member}:${typeName}`]);
}
return [...groups.values()];
}
/** The slot and member names of a group, which tell the five documents apart: the schema id is the C# hash. */
const shape = (members: readonly string[]): string => members.map((member) => member.split(":").slice(0, 2).join(":")).join(",");
for (const [definition, type] of definitions) {
test(`${type}: type, schema and catalog members`, () => {
assert.equal(definition.type, type);
assert.equal(definition.schemaName, type);
assert.equal(definition.schemaVersion, `${type}.v1`);
assert.equal(definition.codec?.typeName, `${NS}${rustName[type]}`);
const actual = definition.members?.map((member) => `${member.slot}:${member.memberName}:${member.typeName}`) ?? [];
const rows = catalogGroups().filter((group) => shape(group) === shape(actual));
assert.equal(rows.length, 1, "exactly one group of the C# catalog has this definition's slots and member names");
assert.deepEqual(actual, rows[0]);
});
}
test("the C# catalog holds the five definitions and nothing else", () => {
const groups = catalogGroups();
assert.equal(groups.length, 5);
assert.equal(new Set(groups.map(shape)).size, 5);
});
test("the registry lists the five definitions, in the crate's order", () => {
assert.deepEqual(
thingContract.definitions.map((definition) => definition.type),
definitions.map(([, type]) => type),
);
assert.equal(new Set(thingContract.definitions).size, 5);
});

View file

@ -0,0 +1,141 @@
// A CommandResult exists only by a factory or by the decode door. Construction is attacked the way an outside consumer
// would: an object literal, JSON.parse output, structuredClone, spread, prototype tricks, the constructor, a Proxy. Each is
// refused where a result is encoded, and none is a CommandResult. The type-level half is test/types.ts.
import assert from "node:assert/strict";
import test from "node:test";
import { decodeDocumentPayload, documentPayloadBytes, documentPayloadFromBytes, encodeDocumentPayload } from "@gamecult/cultcache-ts";
import { CommandResult, commandResultDocument } from "@gamecult/thing-contract";
import { CANARY, golden, invocation, results } from "./builders.js";
const answered = invocation();
const encodeResult = (value: unknown) => () => encodeDocumentPayload(commandResultDocument, value);
const BUILT = /a CommandResult is built by its factories/;
test("a factory copies the invocation id and holds the seq", () => {
const result = CommandResult.failed(answered, 5, "broke");
assert.equal(result.invocationId, answered.invocationId);
assert.equal(result.seq, 5);
assert.deepEqual(result.outcome, { kind: "Failed", reason: "broke" });
assert.ok(result instanceof CommandResult);
assert.ok(CommandResult.isResult(result));
});
test("each factory builds its outcome", () => {
assert.deepEqual(CommandResult.pending(answered, 1, "working").outcome, { kind: "Pending", message: "working" });
assert.deepEqual(CommandResult.completed(answered, 2, 8, true, null).outcome, {
kind: "Completed",
sourceVersion: 8,
clearDrafts: true,
effect: null,
});
assert.deepEqual(CommandResult.denied(answered, 3, "no", "go").outcome, { kind: "Denied", reason: "no", node: "go" });
});
test("a factory refuses seq below 1 naming Seq, and not the value", () => {
for (const bad of [0, -1, -(2 ** 31)]) {
for (const build of [
() => CommandResult.pending(answered, bad, "m"),
() => CommandResult.completed(answered, bad, null, false, null),
() => CommandResult.denied(answered, bad, "r", null),
() => CommandResult.failed(answered, bad, "r"),
]) {
assert.throws(build, (error: Error) => /Seq must be at least 1/.test(error.message) && !error.message.includes(String(bad)));
}
}
assert.throws(() => CommandResult.failed(answered, 1.5, "r"), /int32/);
assert.throws(() => CommandResult.failed(answered, 2 ** 31, "r"), /int32/);
assert.equal(CommandResult.failed(answered, 2 ** 31 - 1, "r").seq, 2 ** 31 - 1);
});
test("the decode door yields a CommandResult instance, equal to the factory's", () => {
for (const [file, value] of results(answered)) {
const decoded = decodeDocumentPayload(commandResultDocument, documentPayloadFromBytes(golden(`${file}.bin`)));
assert.ok(decoded instanceof CommandResult, file);
assert.ok(CommandResult.isResult(decoded), file);
assert.deepStrictEqual(decoded, value, file);
assert.ok(Object.isFrozen(decoded), file);
}
});
test("encoding a result a factory built succeeds, and re-decodes", () => {
const result = CommandResult.pending(answered, 1, "working");
const bytes = documentPayloadBytes(encodeDocumentPayload(commandResultDocument, result));
assert.deepEqual(bytes, golden("result-pending.bin"));
});
test("a copy of a result is not a result: structuredClone, spread and JSON.parse output are refused at encode", () => {
const result = CommandResult.failed(answered, 7, "broke");
for (const [name, copy] of [
["structuredClone", structuredClone(result)],
["spread", { ...result }],
["JSON.parse", JSON.parse(JSON.stringify(result)) as unknown],
["Object.assign", Object.assign({}, result)],
] as const) {
assert.ok(!CommandResult.isResult(copy), name);
assert.ok(!(copy instanceof CommandResult), name);
assert.throws(encodeResult(copy), BUILT, name);
}
});
test("an object literal is not a result", () => {
const literal = { invocationId: answered.invocationId, seq: 1, outcome: { kind: "Failed", reason: "broke" } };
assert.ok(!CommandResult.isResult(literal));
assert.throws(encodeResult(literal), BUILT);
for (const other of [null, undefined, 0, "", "completed", [], {}, () => 0]) {
assert.ok(!CommandResult.isResult(other));
assert.throws(encodeResult(other), BUILT);
}
});
test("prototype tricks do not make a result", () => {
const result = CommandResult.failed(answered, 7, "broke");
const viaCreate = Object.assign(Object.create(CommandResult.prototype) as object, result);
const viaSetPrototype = Object.setPrototypeOf({ ...result }, CommandResult.prototype) as object;
const viaProxy = new Proxy(result, {});
class Impostor extends (CommandResult as unknown as new () => object) {}
for (const [name, fake] of [["Object.create", viaCreate], ["setPrototypeOf", viaSetPrototype], ["Proxy", viaProxy]] as const) {
assert.ok(!CommandResult.isResult(fake), name);
assert.throws(encodeResult(fake), BUILT, name);
}
assert.throws(() => new Impostor(), BUILT);
});
test("the constructor is closed at run time as well as in types", () => {
const construct = CommandResult as unknown as new (...args: unknown[]) => CommandResult;
const outcome = { kind: "Failed", reason: "broke" };
assert.throws(() => new construct(answered.invocationId, 1, outcome), BUILT);
assert.throws(() => new construct(Symbol("door"), answered.invocationId, 1, outcome), BUILT);
assert.throws(() => new construct(undefined, answered.invocationId, 0, outcome), BUILT);
assert.throws(() => Reflect.construct(construct, [answered.invocationId, 0, outcome]), BUILT);
assert.throws(() => Reflect.construct(construct, [], CommandResult), BUILT);
});
test("a result is frozen: a script that ignores types cannot move its seq out of domain", () => {
const result = CommandResult.failed(answered, 7, "broke");
assert.ok(Object.isFrozen(result));
const writable = result as unknown as { seq: number; invocationId: string };
assert.throws(() => {
writable.seq = 0;
}, TypeError);
assert.throws(() => {
writable.invocationId = "other";
}, TypeError);
assert.equal(result.seq, 7);
assert.equal(result.invocationId, answered.invocationId);
});
test("an out-of-domain seq cannot cross the decode door, and no message echoes the payload", () => {
const message = (run: () => unknown) => {
try {
run();
} catch (error) {
return (error as Error).message;
}
return assert.fail("expected a refusal");
};
const refused = message(() => decodeDocumentPayload(commandResultDocument, documentPayloadFromBytes(golden("result-seq-zero.bin"))));
assert.match(refused, /Seq must be at least 1/);
assert.ok(!refused.includes(CANARY));
});

View file

@ -0,0 +1,48 @@
// The value goldens: each file is what the Rust crate writes for the builder's value. Encoding the ported builder gives
// the file byte for byte, decoding the file gives the value back, and re-encoding what was decoded gives the file again.
import assert from "node:assert/strict";
import test from "node:test";
import {
decodeDocumentPayload,
documentPayloadBytes,
documentPayloadFromBytes,
encodeDocumentPayload,
} from "@gamecult/cultcache-ts";
import {
assetCatalogDocument,
commandInvocationDocument,
commandResultDocument,
compositionDocument,
surfaceDocument,
} from "@gamecult/thing-contract";
import { assetCatalogValue, fullComposition, fullSurface, golden, invocation, results } from "./builders.js";
type Case = [file: string, definition: Parameters<typeof encodeDocumentPayload>[0], value: unknown];
const answered = invocation();
const cases: Case[] = [
["surface-all-arms.bin", surfaceDocument, fullSurface()],
["composition-all-params.bin", compositionDocument, fullComposition()],
["invocation-all-inputs.bin", commandInvocationDocument, answered],
...results(answered).map(([name, value]): Case => [`${name}.bin`, commandResultDocument, value]),
["asset-catalog.bin", assetCatalogDocument, assetCatalogValue()],
];
test("the case table names the eleven value goldens", () => {
assert.equal(cases.length, 11);
assert.equal(new Set(cases.map(([file]) => file)).size, 11);
assert.equal(cases.filter(([, definition]) => definition === commandResultDocument).length, 7);
});
for (const [file, definition, value] of cases) {
test(`${file}: the builder encodes to the golden, the golden decodes to the builder, and re-encodes identical`, () => {
const committed = golden(file);
assert.deepEqual(documentPayloadBytes(encodeDocumentPayload(definition, value)), committed);
const decoded = decodeDocumentPayload(definition, documentPayloadFromBytes(committed));
assert.deepStrictEqual(decoded, value);
assert.deepEqual(documentPayloadBytes(encodeDocumentPayload(definition, decoded)), committed);
});
}

View file

@ -0,0 +1,67 @@
// The key grammar of crates/thing-contract/src/keys.rs and the cases of tests/result.rs: keys are built from the fields,
// every local segment is a Segment, and two different field sets never build one key.
import assert from "node:assert/strict";
import test from "node:test";
import { assetCatalogKey, compositionKey, invocationKey, resultKey, surfaceKey } from "@gamecult/thing-contract";
import { CANARY } from "./builders.js";
const builders: [string, (segment: string) => string][] = [
["surfaceKey", (segment) => surfaceKey("p", segment)],
["compositionKey name", (segment) => compositionKey("pub", segment, 1)],
["assetCatalogKey", (segment) => assetCatalogKey("p", segment)],
];
for (const [name, build] of builders) {
test(`${name} refuses an empty, a dot and a dotted segment, naming Segment and not the value`, () => {
assert.throws(() => build(""), /Segment must be non-empty/);
assert.throws(() => build("."), /Segment must be free of '\.'/);
assert.throws(() => build("a.b"), /Segment must be free of '\.'/);
assert.throws(
() => build(`${CANARY}.x`),
(error: Error) => /Segment/.test(error.message) && !error.message.includes(CANARY),
);
});
}
test("the keys are spelled from the fields", () => {
assert.equal(invocationKey("an-invocation-no-constructor-can-guess"), "thing:invocation:an-invocation-no-constructor-can-guess");
assert.equal(resultKey("an-invocation-no-constructor-can-guess", 3), "thing:result:an-invocation-no-constructor-can-guess.3");
assert.equal(surfaceKey("p", "main"), "thing:surface:p.main");
assert.equal(compositionKey("pub", "card", 2), "thing:composition:pub.card.v2");
assert.equal(compositionKey("pub", "card", 2n ** 40n), "thing:composition:pub.card.v1099511627776");
assert.equal(assetCatalogKey("p", "icons"), "thing:asset_catalog:p.icons");
});
test("a result key refuses a seq below 1 and a composition key a version below 0", () => {
assert.throws(() => resultKey("x", 0), /Seq must be at least 1/);
assert.throws(() => compositionKey("pub", "card", -1), /Version must be at least 0/);
assert.equal(compositionKey("pub", "card", 0), "thing:composition:pub.card.v0");
assert.throws(() => compositionKey("pub", "card", 1.5), /int64/);
assert.throws(() => resultKey("x", 1.5), /int32/);
assert.throws(() => resultKey("x", 2 ** 31), /int32/);
});
test("keys are injective over their field sets", () => {
// A dotted provider with a plain label, and a plain provider with a dotted label: the second cannot be built.
assert.equal(surfaceKey("a.b", "c"), "thing:surface:a.b.c");
assert.throws(() => surfaceKey("a", "b.c"), /Segment/);
assert.notEqual(surfaceKey("a", "c"), surfaceKey("a.b", "c"));
assert.notEqual(surfaceKey("a.b", "c"), surfaceKey("a", "bc"));
// A composition splits at its last two dots: publisher, name, then the version.
assert.equal(compositionKey("a.b", "c", 1), "thing:composition:a.b.c.v1");
assert.notEqual(compositionKey("a.b", "c", 1), compositionKey("a", "bc", 1));
assert.notEqual(compositionKey("a", "c", 1), compositionKey("a", "c", 11));
assert.notEqual(compositionKey("a", "c", 1), compositionKey("a", "c", 0));
// A catalog likewise, under the asset_catalog prefix.
assert.equal(assetCatalogKey("a.b", "c"), "thing:asset_catalog:a.b.c");
assert.notEqual(assetCatalogKey("a.b", "c"), assetCatalogKey("a", "bc"));
// A result splits at its last dot, and the seq is digits.
assert.equal(resultKey("x.1", 2), "thing:result:x.1.2");
assert.equal(resultKey("x", 12), "thing:result:x.12");
assert.notEqual(resultKey("x.1", 2), resultKey("x", 12));
});

View file

@ -0,0 +1,67 @@
// The type names the package gives its codecs are the C# package's (tests/thing-contract-parity), and the member names
// follow the owner's: Rust names that C# flattens into arm classes have one codec per arm, a list slot names
// ImmutableArray<T>, and TextInputNode's slot 2 is inputKind, the camelCase of C# InputKind.
import assert from "node:assert/strict";
import { join } from "node:path";
import test from "node:test";
import { codecs } from "@gamecult/thing-contract";
import { nonEmptyLines, parityDir } from "./builders.js";
const NS = "GameCult.Thing.Contract.";
const names = new Set(nonEmptyLines(join(parityDir, "type-names.txt")));
const entries = Object.entries(codecs) as [string, { typeName?: string; members?: readonly { typeName: string }[] }][];
test("Scalar is a Rust name the C# package does not have; ParamName is its type for a slot; each Param arm has its own codec", () => {
assert.equal(names.has(`${NS}Scalar`), false);
for (const [key, codec] of entries) assert.doesNotMatch(codec.typeName ?? "", /.Scalar$/u, key);
assert.ok(names.has(`${NS}ParamName`));
assert.equal(codecs.paramName.typeName, `${NS}ParamName`);
assert.equal(codecs.slotNode.typeName, `${NS}SlotNode`);
const arms = {
textSourceParam: "TextSourceParam",
numberSourceParam: "NumberSourceParam",
boolSourceParam: "BoolSourceParam",
collectionSourceParam: "CollectionSourceParam",
commandRefParam: "CommandRefParam",
dimensionPx: "DimensionPx",
dimensionPercent: "DimensionPercent",
dimensionFr: "DimensionFr",
};
for (const [key, name] of Object.entries(arms)) {
assert.equal((codecs as unknown as Record<string, { typeName: string }>)[key].typeName, `${NS}${name}`, key);
assert.ok(names.has(`${NS}${name}`), name);
}
});
test("a list slot is named ImmutableArray, never List, and the element is a type of the C# package", () => {
let lists = 0;
for (const [key, codec] of entries) {
for (const member of codec.members ?? []) {
if (!/(List|ImmutableArray)</u.test(member.typeName)) continue;
lists++;
const element = /^System\.Collections\.Immutable\.ImmutableArray<(.+)>$/u.exec(member.typeName);
assert.ok(element !== null, `${key}: ${member.typeName}`);
assert.ok(element[1] === "System.String" || names.has(element[1]), `${key}: ${member.typeName}`);
}
}
assert.equal(lists, 14);
});
test("TextInputNode's slot 2 is inputKind, and the name set holds no Kind-only spelling", () => {
const textInputNode = codecs.textInputNode as unknown as { names: readonly string[] };
assert.equal(textInputNode.names[2], "inputKind");
assert.ok(names.has(`${NS}InputKind`));
assert.equal([...names].filter((name) => name.endsWith(".Kind")).length, 0);
});
test("a record keeps its slot names and members through presence, and a union, a list and a leaf carry none", () => {
const shapes = codecs as unknown as Record<string, object>;
for (const record of ["boxNode", "bind", "nodeCommon", "rgba", "dimensionPx"]) {
assert.ok("names" in shapes[record] && "members" in shapes[record], record);
}
for (const other of ["node", "memberStep", "dimension", "colorRef"]) {
assert.ok(!("names" in shapes[other]) && !("members" in shapes[other]), other);
}
});

View file

@ -0,0 +1,84 @@
// The nil vector, written by the Rust crate and read here (crates/thing-contract/tests/goldens/nil-positions.tsv): for
// every array element of every value golden, the golden with that element replaced by nil, and whether Rust's decode
// door accepted it. A slot is required exactly when its Rust type is not optional, so this package keeps no list of
// required slots: it is held to every row, and an accepted row re-encodes to the spliced bytes.
import assert from "node:assert/strict";
import { join } from "node:path";
import test from "node:test";
import {
decodeDocumentPayload,
documentPayloadBytes,
documentPayloadFromBytes,
encodeDocumentPayload,
} from "@gamecult/cultcache-ts";
import {
assetCatalogDocument,
commandInvocationDocument,
commandResultDocument,
compositionDocument,
surfaceDocument,
} from "@gamecult/thing-contract";
import { golden, goldensDir, nonEmptyLines } from "./builders.js";
type Definition = Parameters<typeof decodeDocumentPayload>[0];
const kinds: Record<string, Definition> = {
"surface-all-arms": surfaceDocument,
"composition-all-params": compositionDocument,
"invocation-all-inputs": commandInvocationDocument,
"result-pending": commandResultDocument,
"result-completed": commandResultDocument,
"result-completed-open-surface": commandResultDocument,
"result-completed-open-external": commandResultDocument,
"result-denied": commandResultDocument,
"result-denied-no-node": commandResultDocument,
"result-failed": commandResultDocument,
"asset-catalog": assetCatalogDocument,
};
interface Row {
golden: string;
path: string;
start: number;
end: number;
accept: boolean;
}
const rows: Row[] = nonEmptyLines(join(goldensDir, "nil-positions.tsv")).map((line) => {
const cells = line.split("\t");
assert.equal(cells.length, 5, line);
assert.ok(cells[4] === "ACCEPT" || cells[4] === "REFUSE", line);
return { golden: cells[0], path: cells[1], start: Number(cells[2]), end: Number(cells[3]), accept: cells[4] === "ACCEPT" };
});
test("the vector names every value golden and nothing else", () => {
assert.deepEqual([...new Set(rows.map((row) => row.golden))].sort(), Object.keys(kinds).sort());
assert.ok(rows.length > 1500);
assert.ok(rows.some((row) => row.accept));
});
for (const [name, definition] of Object.entries(kinds)) {
test(`${name}: every nil position is decided as Rust decided it`, () => {
const bytes = golden(`${name}.bin`);
const own = rows.filter((row) => row.golden === name);
assert.ok(own.length > 0);
const wrong: string[] = [];
for (const row of own) {
const spliced = new Uint8Array([...bytes.subarray(0, row.start), 0xc0, ...bytes.subarray(row.end)]);
let decoded: unknown;
try {
decoded = decodeDocumentPayload(definition, documentPayloadFromBytes(spliced));
} catch {
if (row.accept) wrong.push(`${row.path}: refused though Rust accepted`);
continue;
}
if (!row.accept) wrong.push(`${row.path}: accepted though Rust refused`);
else if (!Buffer.from(documentPayloadBytes(encodeDocumentPayload(definition, decoded))).equals(spliced)) {
wrong.push(`${row.path}: accepted but re-encodes to other bytes`);
}
}
assert.deepEqual(wrong.slice(0, 20), [], `${name}: ${wrong.length} rows differ from Rust`);
});
}

View file

@ -0,0 +1,117 @@
// Parity with the C# package, both ways. written-by-cs.cc is a store the C# package's CultCache wrote from its own
// builders (ParityTests.cs writes it); each of its five records re-encodes here to its value golden under keys.ts's
// key. written-by-ts.cc is the store this test writes from the ported builders, and ParityTests.cs reads it the same
// way. THING_PARITY_WRITE=1 rewrites written-by-ts.cc; every other run only reads the committed fixtures and writes a
// temp store whose catalog must equal the C# package's catalog-members.tsv.
import assert from "node:assert/strict";
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
import {
CultCache,
SingleFileMessagePackBackingStore,
documentPayloadBytes,
inspectCultCacheBytes,
} from "@gamecult/cultcache-ts";
import {
CommandResult,
assetCatalogDocument,
assetCatalogKey,
commandInvocationDocument,
commandResultDocument,
compositionDocument,
compositionKey,
invocationKey,
resultKey,
surfaceDocument,
surfaceKey,
thingContract,
} from "@gamecult/thing-contract";
import { assetCatalogValue, fullComposition, fullSurface, golden, invocation, nonEmptyLines, parityDir } from "./builders.js";
const surface = fullSurface();
const composition = fullComposition();
const answered = invocation();
const result = CommandResult.pending(answered, 1, "working");
const catalog = assetCatalogValue();
const records: [key: string, golden: string][] = [
[surfaceKey(surface.providerId, surface.label), "surface-all-arms.bin"],
[compositionKey(composition.publisher, composition.name, composition.version), "composition-all-params.bin"],
[invocationKey(answered.invocationId), "invocation-all-inputs.bin"],
[resultKey(result.invocationId, result.seq), "result-pending.bin"],
[assetCatalogKey(catalog.providerId, catalog.catalogId), "asset-catalog.bin"],
];
function openCache(file: string) {
return CultCache.builder().withRegistry(thingContract).withGenericStore(new SingleFileMessagePackBackingStore(file)).build();
}
async function writeStore(file: string): Promise<void> {
const cache = openCache(file);
await cache.pullAllBackingStores();
await cache.put(surfaceDocument, records[0][0], surface);
await cache.put(compositionDocument, records[1][0], composition);
await cache.put(commandInvocationDocument, records[2][0], answered);
await cache.put(commandResultDocument, records[3][0], result);
await cache.put(assetCatalogDocument, records[4][0], catalog);
}
/** The five records of an opened store each equal their golden's bytes under the package's own key. */
function assertFiveRecords(cache: CultCache): void {
const snapshot = cache.snapshot();
assert.deepEqual(snapshot.map((envelope) => envelope.key).sort(), records.map(([key]) => key).sort());
for (const [key, file] of records) {
const envelope = snapshot.find((candidate) => candidate.key === key);
assert.ok(envelope !== undefined, key);
assert.deepEqual(documentPayloadBytes(envelope.payload), golden(file), key);
}
}
/** A store's catalog as the C# members file prints it, one group per document in the file's order of slots. */
function catalogGroups(rows: string[]): string[] {
const groups = new Map<string, string[]>();
for (const row of rows) {
const [schemaId, slot, member, typeName] = row.split("\t");
groups.set(schemaId, [...(groups.get(schemaId) ?? []), [slot, member, typeName].join("\t")]);
}
return [...groups.values()].map((group) => group.join("\n")).sort();
}
test("a store the C# package wrote opens to five records that re-encode to the goldens", async () => {
const cache = openCache(join(parityDir, "written-by-cs.cc"));
await cache.pullAllBackingStores();
assertFiveRecords(cache);
assert.deepEqual(cache.getRequired(surfaceDocument, records[0][0]), surface);
assert.deepEqual(cache.getRequired(commandResultDocument, records[3][0]), result);
});
test("the store this package writes opens to the same five records, and its catalog is the C# catalog", async () => {
const directory = mkdtempSync(join(tmpdir(), "thing-parity-"));
try {
const file = join(directory, "written-by-ts.cc");
await writeStore(file);
const reopened = openCache(file);
await reopened.pullAllBackingStores();
assertFiveRecords(reopened);
const bytes = new Uint8Array(readFileSync(file));
const mine = inspectCultCacheBytes(file, bytes).catalog.flatMap((entry) =>
entry.members.map((member) => [entry.schemaId, member.slot, member.memberName, member.typeName].join("\t")),
);
assert.deepEqual(catalogGroups(mine), catalogGroups(nonEmptyLines(join(parityDir, "catalog-members.tsv"))));
if (process.env.THING_PARITY_WRITE === "1") writeFileSync(join(parityDir, "written-by-ts.cc"), bytes);
} finally {
rmSync(directory, { recursive: true, force: true });
}
});
test("the committed written-by-ts.cc opens to the five records", async () => {
const cache = openCache(join(parityDir, "written-by-ts.cc"));
await cache.pullAllBackingStores();
assertFiveRecords(cache);
});

View file

@ -0,0 +1,117 @@
// Presence on the encode door and in the factories (the decode door is nil-positions.test.ts). Every builder value with
// one property set to null, or to undefined, is encoded: the encodes the Rust nil vector accepted are the optional
// slots, so the bytes of an accepted encode must be a spliced golden the vector marked ACCEPT, and every ACCEPT row of
// those goldens must be reached. This package keeps no list of required or optional slots.
import assert from "node:assert/strict";
import { join } from "node:path";
import test from "node:test";
import { documentPayloadBytes, encodeDocumentPayload } from "@gamecult/cultcache-ts";
import {
CommandResult,
assetCatalogDocument,
commandInvocationDocument,
commandResultDocument,
compositionDocument,
surfaceDocument,
} from "@gamecult/thing-contract";
import { assetCatalogValue, fullComposition, fullSurface, golden, goldensDir, invocation, nonEmptyLines } from "./builders.js";
type Definition = Parameters<typeof encodeDocumentPayload>[0];
const answered = invocation();
/** The value with the property at `where` replaced; objects and arrays on the way are copied, bytes are shared. */
function replaced(value: unknown, where: (string | number)[], replacement: unknown): unknown {
if (where.length === 0) return replacement;
const [head, ...rest] = where;
if (Array.isArray(value)) return value.map((element, index) => (index === head ? replaced(element, rest, replacement) : element));
const copy: Record<string, unknown> = { ...(value as Record<string, unknown>) };
copy[head as string] = replaced(copy[head as string], rest, replacement);
return copy;
}
/** The path of every property and array element below `value`, parents first. */
function* paths(value: unknown, here: (string | number)[] = []): Generator<(string | number)[]> {
if (Array.isArray(value)) {
for (let index = 0; index < value.length; index++) {
yield [...here, index];
yield* paths(value[index], [...here, index]);
}
} else if (typeof value === "object" && value !== null && !(value instanceof Uint8Array)) {
for (const [key, member] of Object.entries(value)) {
yield [...here, key];
yield* paths(member, [...here, key]);
}
}
}
const hex = (bytes: Uint8Array) => Buffer.from(bytes).toString("hex");
/** The spliced goldens the Rust decode door accepted, as hex. */
function acceptedSplices(name: string): Set<string> {
const bytes = golden(`${name}.bin`);
const accepted = new Set<string>();
for (const line of nonEmptyLines(join(goldensDir, "nil-positions.tsv"))) {
const [file, , start, end, answer] = line.split("\t");
if (file === name && answer === "ACCEPT") {
accepted.add(hex(new Uint8Array([...bytes.subarray(0, Number(start)), 0xc0, ...bytes.subarray(Number(end))])));
}
}
return accepted;
}
const cases: [string, Definition, unknown][] = [
["surface-all-arms", surfaceDocument, fullSurface()],
["composition-all-params", compositionDocument, fullComposition()],
["invocation-all-inputs", commandInvocationDocument, answered],
["asset-catalog", assetCatalogDocument, assetCatalogValue()],
];
for (const [name, definition, value] of cases) {
test(`${name}: a null or undefined property is refused unless Rust made the slot optional`, () => {
const allowed = acceptedSplices(name);
const reached = new Set<string>();
let refused = 0;
for (const where of paths(value)) {
const outcomes = [null, undefined].map((replacement) => {
try {
return hex(documentPayloadBytes(encodeDocumentPayload(definition, replaced(value, where, replacement))));
} catch {
return null;
}
});
assert.equal(outcomes[0], outcomes[1], `${where.join(".")}: null and undefined are decided alike`);
if (outcomes[0] === null) {
refused++;
continue;
}
assert.ok(allowed.has(outcomes[0]), `${where.join(".")}: accepted, and Rust did not accept that nil`);
reached.add(outcomes[0]);
}
assert.ok(refused > 0);
assert.deepEqual([...allowed].filter((splice) => !reached.has(splice)), [], "every optional slot of the golden is reached");
});
}
test("a factory refuses a null message, reason or invocation id at the call", () => {
assert.throws(() => CommandResult.pending(answered, 1, null as unknown as string), /Presence/);
assert.throws(() => CommandResult.pending(answered, 1, undefined as unknown as string), /Presence/);
assert.throws(() => CommandResult.denied(answered, 1, null as unknown as string, null), /Presence/);
assert.throws(() => CommandResult.failed(answered, 1, null as unknown as string), /Presence/);
assert.throws(() => CommandResult.pending({ ...answered, invocationId: null as unknown as string }, 1, "m"), /Presence/);
});
test("completed holds the Version and boolean domains at the call, naming the domain and not the value", () => {
assert.throws(() => CommandResult.completed(answered, 1, -5, false, null), (error: Error) => /Version must be at least 0/.test(error.message) && !error.message.includes("-5"));
assert.throws(() => CommandResult.completed(answered, 1, null, null as unknown as boolean, null), /boolean/);
assert.throws(() => CommandResult.completed(answered, 1, null, undefined as unknown as boolean, null), /boolean/);
const completed = CommandResult.completed(answered, 1, 8, true, null);
assert.equal(completed.outcome.kind, "Completed");
});
test("a valid completed result encodes to result-completed's bytes", () => {
const built = CommandResult.completed(answered, 2, 8, true, null);
assert.deepEqual(documentPayloadBytes(encodeDocumentPayload(commandResultDocument, built)), golden("result-completed.bin"));
});

Some files were not shown because too many files have changed in this diff Show more